
// Open ID
$("#google_reges").click(function(){
    var url = 'https://www.google.com/accounts/o8/id';
    OpenWindow(url);
});
$("#yahoo_reges").click(function(){
    var url = 'https://me.yahoo.com/';
    OpenWindow(url);
});
$("#facebook_reges").click(function(){
    var url = $(".url_facebook").val();
    OpenWindow(url,true);
});
$("#govn_reges").click(function(){
    var url = $(".url_govn").val();
    OpenWindow(url,true);
});

$("#google").click(function(){
    var url = 'https://www.google.com/accounts/o8/id';
    OpenWindow(url);
})
$("#yahoo").click(function(){
    var url = 'https://me.yahoo.com/';
    OpenWindow(url);
})
$("#facebook").click(function(){
    var url = $(".url_facebook").val();
    OpenWindow(url,true);
})
$("#govn").click(function(){
    var url = $(".url_govn").val();
    OpenWindow(url,true);
})

function OpenWindow(url_send,check){
    if(check == true)
        url = url_send;
    else
        url = 'openid/openid.php?url='+url_send;
    var w = screen.availWidth;
    var h = screen.availHeight;
    var left = (screen.width/2)-(w/2) + 5;
    var top = (screen.height/2)-(h/2) - 10;
    window.open(url,'facebook',' width=500, height=500, top='+top+', left='+left);
}
function finish_request(openid_args) {
    var page = $(".page_current").val();
    $.ajax({
        url: 'ajax.php?fnc=openid&path=openid&'+openid_args,
        type:'GET',       
        dataType:'json',
        success:function(data){
            if(page == 'register'){
                $('#openid_form').css('display','none');
                $('#connect_form').css('display','block');
                $(".openid").val(data.url);
                $(".fullname").val(data.name);
                $(".email").val(data.email_open);
                $(".emailopend").val(data.uid);
                $("#current").html(data.current);
                $("#logo_ajax").html(data.logo);
                $("#check_config").val('1');
            }
            else{                
                window.location.replace(data.url_reload);
            }
        }  
    });
}
function completed(){
    url = $("#url_complate").val();
    window.location.reload(url);
}
function lock(){
    jAlert('Tài khoản của bạn đang bị khóa, vui lòng liên hệ ban quản trị để được hỗ trợ','Thông báo');
    
}
function changeImageOpen()
{
	$("#verify_image_open").attr('src',$("#verify_image_open").attr('src')+'&1');
}//process taskbar
$("#text").click(function(){
   var input = $("#text").val();
   if(isNumber(input)){
	 alert("ok");
   }else
	alert("false");
   
});
function isNumber(x) 
{ 
  return ( (typeof x === typeof 1) && (null !== x) && isFinite(x) );
}

//----------------------------------------------
function getUrl(){
	var a = document.location.href;
	var _params = {};
	var paramsRaw = (a.split("?", 2)[1] || "").split('#')[0].split("&") || [];
	for(var i = 0; i < paramsRaw.length; i++){
		var param = paramsRaw[i].split("=");
		if(param[0])
			_params[param[0]] = param[1];
	}
	return _params;
}


//------------------------------------------
//get catalog
$('#account-top li.login_current, #content-aliasx, #support-html, li.support a.show-list').click(function(e) {
	e.stopPropagation(); //Prevents the subpanel ul from closing on click
});


$(document).click(function() { //Click anywhere and...
   $("#account-top li.login_current ul").slideUp(100); //hide subpanel
   $('#account-top li.login_current').children('a').removeClass('active');
   $('#account-top li.login_current').children('ul').removeClass('un_checked');
   closeSupport();
});

$(document).ready(function() {
	$("#account-top li#regeriter").hover(
		function(){
			$(this).children('a').addClass('active');
		},
		function(){
			$(this).children('a').removeClass('active');
		}
	);
	$("#account-top li.login_current").hover(
		function(){
			$(this).children('a').addClass('active');
		},
		function(){
			if($('#account-top li.login_current').children('ul').attr('class') != 'submenu-topbar formLogin un_checked')
				$(this).children('a').removeClass('active');
		}
	);
	$('#account-top li.login_current a.login-title').click(
		function(){
			$('#account-top li.login_current').children('ul').addClass('un_checked');
			$('#account-top li.login_current').children('a').addClass('active');
			$("#account-top li.login_current").children('ul').slideDown(100);
			return false;
		}
	);
	
	$('#btnSearchTaskbar').click(function(){
		
		var txtSearchTaskbar = $("#txtSearchTaskbar").val();
		//txtSearchTaskbar = str_replace(" ", "", txtSearchTaskbar);
		if(txtSearchTaskbar == ""){
			alert("Bạn phải nhập từ khóa tìm kiếm.");
		}
		
	});
	$('#show_sys_admin_menu').click(function(i) { 
		if ($(this).html() == '<span>+ Mở rộng</span>') 
			$(this).html('<span>- Thu gọn</span>');
		else 
			$(this).html('<span>+ Mở rộng</span>');
		$('.sys_admin_menu').animate({"height": "toggle"}, { duration: 200 });
	});
	
	$("#topBar li.view_more_menu").hover(
		  function(){
			if($("#content-aliasx").attr('class') != 'support_active'){
				$(this).children('a').addClass('active');
				$("#list-menu-more-store").slideDown(200);
			}
		  },
		  function(){
			if($("#content-aliasx").attr('class') != 'support_active'){
				$("#list-menu-more-store").slideUp(100);
				$(this).children('a').removeClass('active');
			}
		  }
	  );
	  $("#topBar li.view_support a").click(function(){
		$.get("support.htm",function(data){
			$("#list-menu-more-store").slideUp(100);
			$("#topBar li.view_more_menu").children('a').addClass('active');
			$("#content-aliasx").html(data);
			$("#content-aliasx").addClass('support_active');
			$("#list_data_support").css('top','30px');
			$("#list_data_support").css('left','-265px');
		});
	  });	  
	  $("#topBar li.support").hoverDelay({
		  'over': function() {
				$(this).children('a').addClass('active');
				if($("#support-html").attr('class') == 'clearfix current_view'){
					$("#list_data_support").css('display','block');
					$("#support-html").show();    
				}else{
					$.ajax({
						beforeSend: function(){
							$("#support-html").addClass('current_view');
							$("#support-html").html("Đang tải...").show();  
						},
						cache:true,
						url:"support.htm",
						type:"GET",
						success: function(data){
							$("#support-html").html(data);
						}
					});
				}
		  },
		  'out': function() {
				$(this).children('a').removeClass('active');
				$("#support-html").hide();
		  }
	  })
	  $("#topBar li.ebay_support").hoverDelay({
		  'over': function() {
				$(this).children('a').addClass('active');
				if($("#support-html").attr('class') == 'clearfix current_view'){
					$("#support-html").show();    
				}else{
					$.ajax({
						beforeSend: function(){
							$("#support-html").addClass('current_view');
							$("#support-html").html("Đang tải...").show();  
						},
						cache:true,
						url:"ebay_support.htm",
						type:"GET",
						success: function(data){
							$("#support-html").css('left','-170px');
							$("#support-html").html(data); 
						}
					});
				}              
		  }, 
		  'out': function() {
			  $(this).children('a').removeClass('active');
			  $("#support-html").hide();
		  }
	  })	 	//
//      $("ul#account-top li.hover-view").hover(
//          function(){
//            $(this).children('a').addClass('active');
//            $(".content-navigation").slideDown(200);
//          },
//          function(){
//            $(this).children('a').removeClass('active');
//            //$(".content-navigation").slideUp(200);
//          }
//      );
});
function closeSupport(){
	$("#content-aliasx").removeClass('support_active');
	$("#list_data_support").hide();
	$("#topBar li.view_more_menu").children('a').removeClass('active');
};
var delay;
$("#item-link li.browse").hover(
	function(){
		 var el = $(this);
		 clearTimeout(delay);
		 delay = setTimeout(function(){
			 el.children(".sub-support").show(); 
		 }, 200);
		 
	},
	function(){
		 clearTimeout(delay);
		 $(this).children(".sub-support").hide();
	}   
);

function getKeywordById(id_textbox)
{
	var keyword =  $("#"+id_textbox).val(); 
	keyword = keyword.replace(/([\?*#<>!\$%^&\(\)\/\\]+)/g,"");
	keyword = keyword.replace(/([ ]+)/g," ");
	keyword = keyword.replace(/\"/g, '');
	return keyword;
}

function processFocusById(id_textbox)
{       
	$("#"+id_textbox).val('');    
}
function processBlueById(id_textbox)
{    
	var keyword =  getKeywordById(id_textbox);    
	if(keyword == ''){ 
		$("#"+id_textbox).val("Nhập từ khóa tìm kiếm");
	}   
}
$('#icon_guaranteed').hover(function(){
	$('#show_icon_guaranteed').css('display','block');
}, function() {
	$('#show_icon_guaranteed').css('display','none'); 
});    
$('#icon_shop').hover(function(){
	$('#show_icon_shop').css('display','block');
}, function() {
	$('#show_icon_shop').css('display','none'); 
});  
(function($) {

$.extend($.fn, {
	livequery: function(type, fn, fn2) {
		var self = this, q;

		// Handle different call patterns
		if ($.isFunction(type))
			fn2 = fn, fn = type, type = undefined;

		// See if Live Query already exists
		$.each( $.livequery.queries, function(i, query) {
			if ( self.selector == query.selector && self.context == query.context &&
				type == query.type && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) )
					// Found the query, exit the each loop
					return (q = query) && false;
		});

		// Create new Live Query if it wasn't found
		q = q || new $.livequery(this.selector, this.context, type, fn, fn2);

		// Make sure it is running
		q.stopped = false;

		// Run it immediately for the first time
		q.run();

		// Contnue the chain
		return this;
	},

	expire: function(type, fn, fn2) {
		var self = this;

		// Handle different call patterns
		if ($.isFunction(type))
			fn2 = fn, fn = type, type = undefined;

		// Find the Live Query based on arguments and stop it
		$.each( $.livequery.queries, function(i, query) {
			if ( self.selector == query.selector && self.context == query.context &&
				(!type || type == query.type) && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) && !this.stopped )
					$.livequery.stop(query.id);
		});

		// Continue the chain
		return this;
	}
});

$.livequery = function(selector, context, type, fn, fn2) {
	this.selector = selector;
	this.context  = context;
	this.type     = type;
	this.fn       = fn;
	this.fn2      = fn2;
	this.elements = [];
	this.stopped  = false;

	// The id is the index of the Live Query in $.livequery.queries
	this.id = $.livequery.queries.push(this)-1;

	// Mark the functions for matching later on
	fn.$lqguid = fn.$lqguid || $.livequery.guid++;
	if (fn2) fn2.$lqguid = fn2.$lqguid || $.livequery.guid++;

	// Return the Live Query
	return this;
};

$.livequery.prototype = {
	stop: function() {
		var query = this;

		if ( this.type )
			// Unbind all bound events
			this.elements.unbind(this.type, this.fn);
		else if (this.fn2)
			// Call the second function for all matched elements
			this.elements.each(function(i, el) {
				query.fn2.apply(el);
			});

		// Clear out matched elements
		this.elements = [];

		// Stop the Live Query from running until restarted
		this.stopped = true;
	},

	run: function() {
		// Short-circuit if stopped
		if ( this.stopped ) return;
		var query = this;

		var oEls = this.elements,
			els  = $(this.selector, this.context),
			nEls = els.not(oEls);

		// Set elements to the latest set of matched elements
		this.elements = els;

		if (this.type) {
			// Bind events to newly matched elements
			nEls.bind(this.type, this.fn);

			// Unbind events to elements no longer matched
			if (oEls.length > 0)
				$.each(oEls, function(i, el) {
					if ( $.inArray(el, els) < 0 )
						$.event.remove(el, query.type, query.fn);
				});
		}
		else {
			// Call the first function for newly matched elements
			nEls.each(function() {
				query.fn.apply(this);
			});

			// Call the second function for elements no longer matched
			if ( this.fn2 && oEls.length > 0 )
				$.each(oEls, function(i, el) {
					if ( $.inArray(el, els) < 0 )
						query.fn2.apply(el);
				});
		}
	}
};

$.extend($.livequery, {
	guid: 0,
	queries: [],
	queue: [],
	running: false,
	timeout: null,

	checkQueue: function() {
		if ( $.livequery.running && $.livequery.queue.length ) {
			var length = $.livequery.queue.length;
			// Run each Live Query currently in the queue
			while ( length-- )
				$.livequery.queries[ $.livequery.queue.shift() ].run();
		}
	},

	pause: function() {
		// Don't run anymore Live Queries until restarted
		$.livequery.running = false;
	},

	play: function() {
		// Restart Live Queries
		$.livequery.running = true;
		// Request a run of the Live Queries
		$.livequery.run();
	},

	registerPlugin: function() {
		$.each( arguments, function(i,n) {
			// Short-circuit if the method doesn't exist
			if (!$.fn[n]) return;

			// Save a reference to the original method
			var old = $.fn[n];

			// Create a new method
			$.fn[n] = function() {
				// Call the original method
				var r = old.apply(this, arguments);

				// Request a run of the Live Queries
				$.livequery.run();

				// Return the original methods result
				return r;
			}
		});
	},

	run: function(id) {
		if (id != undefined) {
			// Put the particular Live Query in the queue if it doesn't already exist
			if ( $.inArray(id, $.livequery.queue) < 0 )
				$.livequery.queue.push( id );
		}
		else
			// Put each Live Query in the queue if it doesn't already exist
			$.each( $.livequery.queries, function(id) {
				if ( $.inArray(id, $.livequery.queue) < 0 )
					$.livequery.queue.push( id );
			});

		// Clear timeout if it already exists
		if ($.livequery.timeout) clearTimeout($.livequery.timeout);
		// Create a timeout to check the queue and actually run the Live Queries
		$.livequery.timeout = setTimeout($.livequery.checkQueue, 20);
	},

	stop: function(id) {
		if (id != undefined)
			// Stop are particular Live Query
			$.livequery.queries[ id ].stop();
		else
			// Stop all Live Queries
			$.each( $.livequery.queries, function(id) {
				$.livequery.queries[ id ].stop();
			});
	}
});

// Register core DOM manipulation methods
$.livequery.registerPlugin('append', 'prepend', 'after', 'before', 'wrap', 'attr', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'empty', 'remove', 'html');

// Run Live Queries when the Document is ready
$(function() { $.livequery.play(); });

})(jQuery);(function($){
	
	$.extend({
			 
		anchors : function(speed, easing,urlCustom,redirect){
				
			var scrollElement = 'html, body';
			$('html, body').each(function () {
				var initScrollTop = $(this).attr('scrollTop');
				$(this).attr('scrollTop', initScrollTop + 1);
				if ($(this).attr('scrollTop') == initScrollTop + 1) {
					scrollElement = this.nodeName.toLowerCase();
					$(this).attr('scrollTop', initScrollTop);
					return false;
				}    
			});
				
			speed = speed || "fast";
			easing = easing || null;
			redirect = (redirect === true) ? true : false;
			//alert(redirect);
			
			$("a.anchor").each(function(i){
                url = urlCustom || $(this).attr("rel"); 
				if(url){
					if(url.indexOf("#") != -1 && url.indexOf("#") == 0){
		
						var aParts = url.split("#",2);
						var anchor = $("#"+aParts[1]);
						
						if(anchor){
																					
							$(this).click(function(){
												   
								if($(document).height()-anchor.offset().top >= $(window).height()
								 || anchor.offset().top > $(window).height()
								 || $(document).width()-anchor.offset().left >= $(window).width()
								 || anchor.offset().left > $(window).width()){
												   
									$(scrollElement).animate({
										scrollTop: (anchor.offset().top - 35),
										scrollLeft: anchor.offset().left
									}, speed, easing, function(){
										if(redirect){ 
											window.location = url 
										}
									});
								
								}
								
								return false;
																
							});
						}
					
					}
					
				}
				
			});
			
		}
	
	});
	
})(jQuery);
$.anchors(); 
(function($) {
	
	$.alerts = {
		
		// These properties can be read/written by accessing $.alerts.propertyName from your scripts at any time
		
		verticalOffset: -75,                // vertical offset of the dialog from center screen, in pixels
		horizontalOffset: 0,                // horizontal offset of the dialog from center screen, in pixels/
		repositionOnResize: true,           // re-centers the dialog on window resize
		overlayOpacity: .01,                // transparency level of overlay
		overlayColor: '#FFF',               // base color of overlay
		draggable: false,                    // make the dialogs draggable (requires UI Draggables plugin)
		okButton: '&nbsp;Đồng ý&nbsp;',         // text for the OK button
		cancelButton: '&nbsp;Bỏ qua&nbsp;', // text for the Cancel button
		dialogClass: null,                  // if specified, this class will be applied to all dialogs
		
		// Public methods
		
		alert: function(message, title, callback) {
			if( title == null ) title = 'Thông báo';
			$.alerts._show(title, message, null, 'alert', function(result) {
				if( callback ) callback(result);
			});
		},
		
		confirm: function(message, title, callback) {
			if( title == null ) title = 'Xác nhận';
			$.alerts._show(title, message, null, 'confirm', function(result) {
				if( callback ) callback(result);
			});
		},
			
		prompt: function(message, value, title, callback) {
			if( title == null ) title = 'Prompt';
			$.alerts._show(title, message, value, 'prompt', function(result) {
				if( callback ) callback(result);
			});
		},
		
		// Private methods
		
		_show: function(title, msg, value, type, callback) {
			
			$.alerts._hide();
			$.alerts._overlay('show');
			
			$("BODY").append(
			  '<div id="popup_container">' +
			    '<h1 id="popup_title"></h1>' +
			    '<div id="popup_content">' +
			      '<p id="popup_message"></p>' +
				'</div>' +
			  '</div>');
			
			if( $.alerts.dialogClass ) $("#popup_container").addClass($.alerts.dialogClass);
			
			// IE6 Fix
			var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed'; 
			
			$("#popup_container").css({
				position: pos,
				zIndex: 99999,
				margin: 0
			});
			
			$("#popup_title").text(title);
			$("#popup_content").addClass(type);
			$("#popup_message").text(msg);
			$("#popup_message").html( $("#popup_message").text().replace(/\n/g, '<br />') );
			
			$("#popup_container").css({
				minWidth: $("#popup_container").outerWidth(),
				maxWidth: $("#popup_container").outerWidth()
			});
			
			$.alerts._reposition();
			$.alerts._maintainPosition(true);
			
			switch( type ) {
				case 'alert':
					$("#popup_message").after('<div id="popup_panel"><input class="submit-orange" type="button" value="' + $.alerts.okButton + '" id="popup_ok" /></div>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						callback(true);
					});
					$("#popup_ok").focus().keypress( function(e) {
						if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click');
					});
				break;
				case 'confirm':
					$("#popup_message").after('<div id="popup_panel"><input class="submit-orange" type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" class="submit-dark"/></div>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						if( callback ) callback(true);
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback(false);
					});
					$("#popup_ok").focus();
					$("#popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
				break;
				case 'prompt':
					$("#popup_message").append('<br /><input type="text" size="30" id="popup_prompt" />').after('<div id="popup_panel"><input class="submit-orange" type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" class="submit-dark"/></div>');
					$("#popup_prompt").width( $("#popup_message").width() );
					$("#popup_ok").click( function() {
						var val = $("#popup_prompt").val();
						$.alerts._hide();
						if( callback ) callback( val );
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback( null );
					});
					$("#popup_prompt, #popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
					if( value ) $("#popup_prompt").val(value);
					$("#popup_prompt").focus().select();
				break;
			}
			
			// Make draggable
			if( $.alerts.draggable ) {
				try {
					$("#popup_container").draggable({ handle: $("#popup_title") });
					$("#popup_title").css({ cursor: 'move' });
				} catch(e) { /* requires jQuery UI draggables */ }
			}
		},
		
		_hide: function() {
			$("#popup_container").remove();
			$.alerts._overlay('hide');
			$.alerts._maintainPosition(false);
		},
		
		_overlay: function(status) {
			switch( status ) {
				case 'show':
					$.alerts._overlay('hide');
					$("BODY").append('<div id="popup_overlay"></div>');
					$("#popup_overlay").css({
						position: 'absolute',
						zIndex: 99998,
						top: '0px',
						left: '0px',
						width: '100%',
						height: $(document).height(),
						background: $.alerts.overlayColor,
						opacity: $.alerts.overlayOpacity
					});
				break;
				case 'hide':
					$("#popup_overlay").remove();
				break;
			}
		},
		
		_reposition: function() {
			var top = (($(window).height() / 2) - ($("#popup_container").outerHeight() / 2)) + $.alerts.verticalOffset;
			var left = (($(window).width() / 2) - ($("#popup_container").outerWidth() / 2)) + $.alerts.horizontalOffset;
			if( top < 0 ) top = 0;
			if( left < 0 ) left = 0;
			
			// IE6 fix
			if( $.browser.msie && parseInt($.browser.version) <= 6 ) top = top + $(window).scrollTop();
			
			$("#popup_container").css({
				top: top + 'px',
				left: left + 'px'
			});
			$("#popup_overlay").height( $(document).height() );
		},
		
		_maintainPosition: function(status) {
			if( $.alerts.repositionOnResize ) {
				switch(status) {
					case true:
						$(window).bind('resize', $.alerts._reposition);
					break;
					case false:
						$(window).unbind('resize', $.alerts._reposition);
					break;
				}
			}
		}
		
	};
	
	// Shortuct functions
	jAlert = function(message, title, callback) {
		$.alerts.alert(message, title, callback);
	};
	
	jConfirm = function(message, title, callback) {
		$.alerts.confirm(message, title, callback);
	};
		
	jPrompt = function(message, value, title, callback) {
		$.alerts.prompt(message, value, title, callback);
	};
	
})(jQuery);/*
 * jGD DropDown
 * Version 0.4 (18-SEP-2010)
 * @requires jQuery v1.3 or later
 *
 * Homepage: http://www.dev4press.com/jquery/jgd-dropdown/
 * Examples: http://www.dev4press.com/jgd/dropdown/
 * 
 * Copyright (c) 2008-2010 Milan Petrovic, Dev4Press
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Thanks to Janko at Warp Speed for this great article:
 * http://www.jankoatwarpspeed.com/post/2009/07/28/reinventing-drop-down-with-css-jquery.aspx
 */

(function($){
    $.fn.jgdDropdown = function(options) {
        var settings =  $.extend({}, $.fn.jgdDropdown.defaults, options);
        return this.each(function() {
            var $this = $(this);
            var $id = $.fn.jgdDropdown.convert($this, settings);

            $("#" + $id + " dt a").click(function() {
                $("#" + $id + " dd ul").toggle();
                return false;
            });

            $(document).bind('click', function(e) {
                var $clicked = $(e.target);
                if (!$clicked.parents().hasClass(settings.cls)) {
                    $("." + settings.cls + " dd ul").hide();
                }
            });

            $("#" + $id + " dd ul li a").click(function() {
                var $sel = $(this);
                var $val = $sel.find("span.value").html();
                $this.val($val);
                $("#" + $id + " dt a").html($sel.html());
                $("#" + $id + " dd ul").hide();
                if (settings.clsCopySelect) {
                    $("#" + $id + " dt").attr("class", $sel.parent().attr("class"));
                }
                $sel.parent().parent().find("li").removeClass(settings.clsLISelected);
                $sel.parent().addClass(settings.clsLISelected);
                if (settings.callback) {
                    settings.callback($this, $val);
                }
                return false;
            });
        });
    };
    $.fn.jgdDropdown.defaults = {
        callback: null,
        cls: 'jgd-dropdown',
        initTitle: '',
        forceTitle: false,
        clsLIPrefix: '',
        clsLISelected: 'selected',
        clsCopySelect: true,
        clsLIExpand: true,
        selected: ''
    };
    $.fn.jgdDropdown.convert = function($obj, settings) {
        var iTitle = settings.initTitle;
        var iVal = '';
        if (settings.selected !== null && settings.selected !== '') {
            $obj.val(settings.selected);
            if (!settings.forceTitle) {
                iTitle = '';
            }
        }
        var selected = $obj.find("option:selected");
        var options = $("option", $obj);
        var id = "jgd_dd_" + get_id($obj);
        $obj.after('<li id="' + id + '" class="' + settings.cls + '"></li>');
        if (iTitle === '') {
            iTitle = selected.text();
            iVal = selected.val();
        }
        $("#" + id).append('<dt><a href="#">' + iTitle + '<span class="value">' + iVal +  '</span></a></dt>');
        $("#" + id).append('<dd><ul></ul></dd>');
        options.each(function(index){
            var elClass = $(this).attr("class");
            var elStyle = $(this).attr("style");

            var cls = settings.clsLIPrefix + $(this).val();
            if (settings.clsLIExpand) {
                cls += " item-" + index;
                cls += " item-" + ($.fn.jgd.isEven(index) ? "even" : "odd");
                if (index === 0) {
                    cls += " item-first";
                }
                if (index == options.length - 1) {
                    cls += " item-last";
                }
                if(elClass && elClass !== '') {
                    cls+= " " + thisclass;
                }
            }
            if (settings.clsCopySelect) {
                $("#" + id + " dt").attr("class", cls);
            }
            if ($(this).val() == selected.val()) {
                cls += " " + settings.clsLISelected;
            }
            $("#" + id + " dd ul").append('<li class="' + cls + '"><a href="#">' +
                $(this).text() + '<span class="value">' + $(this).val() + '</span></a></li>');
            if (elStyle) {
                $("#" + id + " dd ul").find("li:last a").attr("style", elStyle);
            }
        });
        $obj.hide();
        return id;
    };
    $.fn.jgd = function() {};
    $.fn.jgd.isEven = function($num) {
        return ($num%2 === 0);
    };
    function get_id($obj) {
        var id = $obj.attr("id");
        if (id === "") {
            id = random_id();
        }
        return id;
    }
    function random_id() {
        var dt = new Date().getMilliseconds();
        var num = Math.random();
        var rnd = Math.round(num * 100000);
        return "jgd" + dt + rnd;
    }
    function debug($obj) {
        if (window.console && window.console.log) {
             window.console.log('jgd_dropdown: ' + $obj.size());
        }
    }
})(jQuery);

	$(".show-list").click( function(){		
		openPopup($(this));
	});				
	$(".show-tip").mouseover(function(){		
		openPopup($(this));
	});
	$(".popup-close").click(function(){			
		closePopup();
	});
	$(".close").click(function(){			
		closePopup();
	});
	
	$(".button-close").click(function(){			
		closePopup();
	});
	$(".popup-background").click(function(){
		closePopup();
	});
	
	$(document).keypress(function(e){
		if(e.keyCode==27 && popupFlag==1){
			closePopup();
		}
	});		
	
	var popupFlag = 0;
	
	function openPopup(obj){
		if(popupFlag==0){			
			//var pos = obj.position();	
			var thisParent = obj.parent();
			//var parentTop = thisParent.offset().top;
			var parentTop = obj.position().top;
			var rel = obj.attr('rel');
			var windowWidth = $(window).width();
			var windowHeight = $(window).height();
			var divWidth = $("#"+rel).width(); 
			var divHeight = $("#"+rel).height(); 
			var left = (windowWidth - divWidth)/2;
			//var left = thisParent.offset().left + obj.width()/2 -  divWidth/2;
			if(left+divWidth > windowWidth) left = windowWidth - divWidth;
			var sp = rel.split('-');
			var name = sp[0];
			var id = sp[1];	
			//var top = parentTop + divHeight + 10;
			var top = - (divHeight)/2;
			$("#"+name+"-"+id).css({
				"position": "absolute",
				"top": (windowHeight-divHeight) / 2+getPageScroll()[1],				
				"left" : left
				//"top": pos.top,
				//"left": pos.left				
			});		
	
			$(".popup-background").css({
				"-moz-opacity": 0,
				"opacity": 0.0,
				"z-index": 10,								
				"top": 0,
				"left": 0
			});
	
			$(".popup-background").fadeIn("fast");
			
			$("#"+name+"-"+id).fadeIn("fast");
			
			popupFlag = rel;
		}
	}
	 function getPageScroll() {
		    var xScroll, yScroll;
		    if (self.pageYOffset) {
		      yScroll = self.pageYOffset;
		      xScroll = self.pageXOffset;
		    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		      yScroll = document.documentElement.scrollTop;
		      xScroll = document.documentElement.scrollLeft;
		    } else if (document.body) {// all other Explorers
		      yScroll = document.body.scrollTop;
		      xScroll = document.body.scrollLeft;	
		    }
		    return new Array(xScroll,yScroll) 
		  }
	function closePopup(){
		if(popupFlag != 0){
			$(".popup-background").fadeOut("fast");
			$(".popup-choose").fadeOut("fast");
			resetForm('form-'+popupFlag);
			popupFlag = 0;
		}
	}
	
	function resetForm(id) {
		if($('#'+id).length > 0)
		{
			$('#'+id).each(function(){
		        this.reset();
			});
		}		
	}jQuery.cookie = function (key, value, options) {

	// key and value given, set cookie...
	if (arguments.length > 1 && (value === null || typeof value !== "object")) {
		options = jQuery.extend({}, options);

		if (value === null) {
			options.expires = -1;
		}

		if (typeof options.expires === 'number') {
			var days = options.expires, t = options.expires = new Date();
			t.setDate(t.getDate() + days);
		}

		return (document.cookie = [
			encodeURIComponent(key), '=',
			options.raw ? String(value) : encodeURIComponent(String(value)),
			options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
			options.path ? '; path=' + options.path : '',
			options.domain ? '; domain=' + options.domain : '',
			options.secure ? '; secure' : ''
		].join(''));
	}

	// key and possibly options given, get cookie...
	options = value || {};
	var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
	return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

/**
* Jquery Notification Chodientu.vn
* requied jgrowl , jCookie
* @Customize by HanVanLoi
* @created 10-04-2010
* @extends Jquery Notification
*/
(function($){
	$.notice = function(number, options) { 
		//hien thi so luong
		var els = $(options.noticeDiv);
		if (els.length>1) els = els[0];
		els = $(els);
		var num = parseInt(els.text()) + number;
		
		if(num>0) 
			 $(options.noticeDiv).html(num).show();
	};
	
	$.notice.pview = function( product_id, options ){
		if(product_id =="undefined" || product_id==0 || product_id=="") return;
		var cookie_name = 'product_view';
		
		var cookie_time = 'time_product_view';                
						
		var options = { path: '/', expires: 10 };
		var value  =  $.cookie(cookie_name);
		var time_value  = $.cookie(cookie_time);
		
		
		if(value !="" && value != null && value !='undefined' && time_value !=null && time_value != "" && time_value !='undefined'){
			var arr =  value.split(",");
			//if(time_value !="" && time_value != null && time_value !='undefined')
			var arr_time = time_value.split(',');
			
			if($.inArray(product_id,arr) == -1){
				if(arr.length >=5){
				  arr.pop();
				  value = product_id + "," + arr.toString();
				  arr_time.pop();
				  value_time = new Date().getTime()+"," + arr_time.toString();
				}else{
				  value =  product_id + "," + value ;
				  value_time = new Date().getTime() +"," + time_value;
				}
				// add thêm sản phẩm vào cookie
				$.cookie(cookie_name, value, options);
				// add số lượng chưa xem trên notice
				$.notice.addNumCookie('num_pview',options);
				
				//add time cookies
				$.cookie(cookie_time, value_time, options);
				
				return $.notice(1, $.extend( {}, options, { noticeDiv : "#pView"}));
			}
		}else{
			value = product_id;
			$.cookie(cookie_name, value, options);
			// add số lượng chưa xem trên notice
			$.notice.addNumCookie('num_pview',options);
			//Cookie time                                   
			$.cookie(cookie_time, new Date().getTime(), options);
						 
			return $.notice(1, $.extend( {}, options, { noticeDiv : "#pView"})); 
		}
													
	};
	$.notice.pcart = function(number, options ){
		var cookie_name = 'num_pcart';
		var options = { path: '/', expires: 10 };
		// add số lượng chưa xem trên notice 
		$.notice.addNumCookie(cookie_name,options);        
		return $.notice(number, $.extend( {}, options, { noticeDiv : ".pCart"}));
	};
	// báo số trên notification
	$.notice.alert = function(number, options ){
		return $.notice(number, $.extend({}, options, { noticeDiv : "#nAlert" }));
	};
	
	$.notice.psave = function(number, options ){
		var cookie_name = 'num_psave'; 
		var options = { path: '/', expires: 10 };
		// add số lượng chưa xem trên notice 
		$.notice.addNumCookie(cookie_name,options);
		return $.notice(number, $.extend( {}, options, { noticeDiv : "#pSave" }));
	};
	
	$.notice.addNumCookie = function (cookie_name,options){
		var value  =  $.cookie(cookie_name);
		if(value !="" && value != null){
			value_pview = parseInt(value) + 1; 
			$.cookie(cookie_name, value, options);    
		}else{
			 value = 1; 
			 $.cookie(cookie_name, value, options);  
		}
	};
	// xoá cookie
	$.notice.resetNumCookie = function(cookie_name){
		  var options = { path: '/', expires: 10 }; 
		  $.cookie(cookie_name, 0,options);
	};
	$.notice.showAlert = function (content, options){   
		return $.jGrowl(content,options);  
	};

	$.notice.load = function(href,notice_id,requie,cookie_type){
		if(requie && user_id == 0) { return false;}
		$.ajax({
			beforeSend : function(){
				 //$(notice_id).children('li.img-loading').slideDown();                 
			},
		   url : href,
		   dataType: 'json',
		   type: "GET",
		   success: function(data){                
			   switch(cookie_type){                   
				   case 2 :
						$(notice_id).html(data.content).parents(".subalert").show(500);
						$('span.num-notify').hide();
						break;
			   }
		   }
		})
	};
	
	//Cookie dem so lan load page - adv
	$.notice.numLoad=function(value,options){
		var options = { path: '/', expires: 1 };            
		$.cookie('num_load', value, options);
	};
	
	$.notice.numLoadTime=function(options){
		var options = { path: '/', expires: 1 };
		$.cookie('num_load_time', new Date().getTime(), options);        
	};
	
	$.notice.defaults = {
			noticeDiv: "notice",
			effect : "fade"
		};    
})(jQuery);$(document).ready(function(){
        var w_header = $('div.ps-heartbanner').width();
      //  console.log('1:' + w_header);
        //chiểu rộng hiện tại của flash
        if($('#header-banner').length){
            //chiều rộng hiện tại của flash
            var cur_w = $('#header-banner').attr('width');
     //       console.log('2:' + cur_w);  
            //chiều cao hiện tại của flash
            var cur_h = $('#header-banner').attr('height');
     //       console.log('3:' + cur_h);  
            //chiều rộng bằng chiều rộng của trang
            var w_display = w_header;
            //chiều cao theo đúng tỉ lệ
            var h_display = cur_h*(w_header/cur_w);
            h_display =  Math.ceil(h_display); 
     //       console.log('4:' + h_display);
            //set kích thước mới cho flash
            $('#header-banner').attr('width',w_display);
            $('#header-banner').attr('height',h_display);
        }
});$(document).ready(function(){
   $('.show-list-more').click(function(){
       var path_icon = $('#icon_path').val();
        
       if ($('.show-more').is( ":visible" )){ 
           $('.show-more').slideUp('fast');
           $(this).html('<img src="'+path_icon+'moreNav.gif">');
        }
        else{
            $('.show-more').slideDown('fast');
            $(this).html('<img src="'+path_icon+'moreNav_act.gif">');
        }         
   }); 
   $('.show-more').mouseleave(function(){  
        var path_icon = $('#icon_path').val(); 
        $('.show-list-more').html('<img src="'+path_icon+'moreNav.gif">');
        $(this).slideUp('fast');
   });
   $('#menu-navi').mouseleave(function(){
          var path_icon = $('#icon_path').val(); 
        $('.show-list-more').html('<img src="'+path_icon+'moreNav.gif">');
        $('.show-more').slideUp('fast');
   });
   $('.set-up-shop').mouseover(function(){
        $('.menu_admin').slideUp('fast'); 
        $('.menu-shop').slideDown('fast');
        var path_icon = $('#icon_path').val(); 
        $('.show-list-more').html('<img src="'+path_icon+'moreNav.gif">'); 
        $('.show-more').slideUp('fast');
   });
   $('.setup-item').mouseleave(function(){
        $('.menu-shop').slideUp('fast');
        $('.menu_admin').slideUp('fast');
   });
   
   $('.admin_shop').mouseover(function(){
        $('.menu-shop').slideUp('fast');
        $('.menu_admin').slideDown('fast');
        $(this).die();
   });  
});    $("#min_price").blur(function(){
        var _text = $("#min_price").val();        
        if(_text == '')
        {
            $("#min_price").val("Giá từ");
        }            
    }).focus(function(){
        var _text = $("#min_price").val();
        if(_text == 'Giá từ')
        {
            $("#min_price").val("");
        }        
    });   
    
    $("#max_price").blur(function(){
        var _text = $("#max_price").val();        
        if(_text == '')
        {
            $("#max_price").val("Giá đến");
        }            
    }).focus(function(){
        var _text = $("#max_price").val();
        if(_text == 'Giá đến')
        {
            $("#max_price").val("");
        }        
    });  
    $("#keyword").blur(function(){
        var _text = $("#keyword").val();        
        if(_text == '')
        {
            $("#keyword").val("Nhập từ khóa");
        }            
    }).focus(function(){
        var _text = $("#keyword").val();
        if(_text == 'Nhập từ khóa')
        {
            $("#keyword").val("");
        }        
    });
    $("form[name='StoreSearchForm']").submit(function(){
        var _condition = '';        
        var _keyword = $("#keyword").val();
        var _minPrice = parseInt(StoreSearchFormPrice($("#min_price").val()));
        var _maxPrice  = parseInt(StoreSearchFormPrice($("#max_price").val()));        
        var _storeName = $("#store_name").val();
        //Kiem tra gia thap nhat
        if((_minPrice && isNaN(_minPrice)) || (_maxPrice && isNaN(_maxPrice)))
        {
            jAlert('Giá nhập vào phải là số.','Cảnh báo');
            return false; 
        }
        //Kiem tra hop le khoang gia
        if(_minPrice > _maxPrice)
        {
            jAlert('Bạn nhập khoảng giá không hợp lệ. Giá nhỏ nhất phải nhỏ hơn giá lớn nhất.','Cảnh báo');
            return false;
        }
        if(_minPrice > 0)
        {            
             _condition += "price_min=" + _minPrice;
        }
        if(_maxPrice > 0)
        {
            if(_condition == '')
                _condition += "price_max=" + _maxPrice;
            else
                _condition += "&price_max=" + _maxPrice;
        }
        if(_condition == '')        
        {
            if(_keyword == '' || _keyword == 'Nhập từ khóa')
            {
                jAlert('Bạn chưa nhập từ khóa tìm kiếm','Cảnh báo');
                return false; 
            }
        }
        if(_keyword != '' && _keyword != 'Nhập từ khóa')
        {
            if(_condition != '')
                _condition = "/tim-kiem/?keyword=" + encodeURIComponent(_keyword) + '&' + _condition ;    
            else
                _condition = "/tim-kiem/?keyword=" + encodeURIComponent(_keyword);    
        }else
        {
            _condition = "/tim-kiem/?" + _condition;     
        }        
        var rootUrl=$("form[name='StoreSearchForm']").attr('rel');           
        window.location.href = _storeName + _condition;
        return false;
    });       
    // ham chinh sua gia ve kieu double
    function StoreSearchFormPrice(price)
    {
        var price = price.replace(/\./g, "");
        var price = price.replace(/,/g, "");
        return price;
    }    function addEvent( obj, type, fn ) {
    if (obj.addEventListener) {
        obj.addEventListener( type, fn, false );
        EventCache.add(obj, type, fn);
    }
    else if (obj.attachEvent) {
        obj["e"+type+fn] = fn;
        obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
        obj.attachEvent( "on"+type, obj[type+fn] );
        EventCache.add(obj, type, fn);
    }
    else {
        obj["on"+type] = obj["e"+type+fn];
    }
};
var EventCache = function(){
    var listEvents = [];
    return {
        listEvents : listEvents,
        add : function(node, sEventName, fHandler){
            listEvents.push(arguments);
        },
        flush : function(){
            var i, item;
            for(i = listEvents.length - 1; i >= 0; i = i - 1){
                item = listEvents[i];
                if(item[0].removeEventListener){
                    item[0].removeEventListener(item[1], item[2], item[3]);
                };
                if(item[1].substring(0, 2) != "on"){
                    item[1] = "on" + item[1];
                };
                if(item[0].detachEvent){
                    item[0].detachEvent(item[1], item[2]);
                };
                item[0][item[1]] = null;
            };
        }
    };
}();
addEvent(window,'unload',EventCache.flush);
function KeypressThrow(e){
    if(window.event)
         window.event.returnValue = null;
    else
       if(e.preventDefault)
            e.preventDefault();
            e.returnValue = false;
    return false;    
};

function isLocked(e){
    KeypressThrow(e);
};

function isNumeric(e){
    var key =(window.event) ? window.event.keyCode:e.charCode;
    var nkey = String.fromCharCode(key);
    if(key !=0 && nkey.match(/[^0-9]/)){
       KeypressThrow(e);
    }
};

function isCurrency(e){
    var key =(window.event) ? window.event.keyCode:e.charCode;
    var nkey = String.fromCharCode(key);
    var el = getTarget(e); 
    var arr_val = el.value.split(','); 
    hasDot = (el.value.indexOf(",") ==-1) ? false:(key ==44 || key !=0 && arr_val[1] && arr_val[1].length==2) ? true:false;
    if(hasDot || key !=0 && nkey.match(/[^0-9,]/)){
        KeypressThrow(e);
    }
    
};

function getCaretPos(elm)
{
     var cpos = 0;
     if (document.selection) { 
         elm.focus ();
         var oSel = document.selection.createRange();
         oSel.moveStart ('character', -elm.value.length);
         cpos = oSel.text.length;
     }else if (elm.selectionStart || elm.selectionStart == '0'){
         cpos = elm.selectionStart;
     }    
     return (cpos);
};
   
function setCaretPos(elm, cpos)
{
     if (document.selection) { 
         elm.focus();
         var oSel = document.selection.createRange();
         oSel.moveStart ('character', -elm.value.length);
         oSel.moveStart ('character', cpos);
         oSel.moveEnd ('character', 0);
      //  oSel.select ();
     }else if (elm.selectionStart || elm.selectionStart == '0') {
         elm.selectionStart = cpos;
         elm.selectionEnd = cpos;
         elm.focus();
     }
};

function CurFormat(e){
var el = getTarget(e);  
var tmp1 = '';
  var elm='';
  elm  = RemStr(el.value,'.');
  if(el.maxLength<0){
     el.setAttribute('maxLength','15') 
  }     
  if(el.maxLength > el.value.length -1){
    if(elm.indexOf(',') !=-1){
       arr_val = elm.split(",");
       tmp1 = FormatCurrency(arr_val[0])+','+ arr_val[1];
       el.value = tmp1;//substring(0,tmp1.length -1);
     
    }else{
       var key =(window.event) ? window.event.keyCode:e.charCode;
       var caret = 0;
       caret = getCaretPos(el);      
       if(key ==0 || key == 44 ){
           tmp1 = FormatCurrency(elm);
           el.value = tmp1; //.substring(0,tmp1.length -1);
       }   
       if(key > 48){
           tmp1 = FormatCurrency(elm);
           el.value = tmp1; //.substring(0,tmp1.length -1);
       }
   //    setCaretPos(el,caret);  
     }
    
  }
 //el.focus();
};
    function RemStr(data,schar){
        var tmpStr='';
        if(data && data.indexOf('.')!=-1){
            tmpStr = data.replace(/[.]/g,'');
         }else{
            tmpStr = data;
        }
        return tmpStr;
    }
        function FormatCurrency(data){
            var tmp1='';
            var num=''; 
            var i = 0;
            tmp1 = insComma(data);
            var total = tmp1.length;
           for (i = total-1; i >= 0; i--) 
           {
              num += tmp1.charAt(i);
           }         
            return num;
        }
            function insComma(data){
               var count = 0;
               var i = 0;
               var tmpStr = "";
               var comma = ".";
            
              for (i = (data.length)-1; i >= 0; i--) {
                  if (count == 3){
                     tmpStr += comma;
                     count = 1;
                  }else 
                     count ++;
                  if(data.charAt(i)==',')
                  {
                     count = 0;
                     tmpStr = tmpStr.replace(/[.]/g,'');
                  }      
                  tmpStr += data.charAt(i); 
               }
               return tmpStr;
            };

function DateFormat(e){
    var obj = getTarget(e);
     var date = obj.value;
    var    dkey = (window.event) ? window.event.keyCode:e.charCode;
    if(dkey != 46){
        if (/^\d{2}$/.test(date)){
            obj.value=obj.value+'/'; return false; 
        }
        if (/^\d{2}\/\d{2}$/.test(date)){
            obj.value=obj.value+'/'; return false; 
        }
        if (/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(date)){
            return false; 
        }
    }
};

function getTarget(e){
    var target = window.event ? window.event.srcElement : e ? e.target : null;
    if (!target){
      return false;
    }else{
      return target;
    }
};

function addKeypressListener(){
  var el = document.getElementsByTagName('input');
  var elm = [];
  if(typeof el.length != 'number'){
      var count=0;
      while (typeof el[count] != 'undefined') {
         els = el[count]; 
         if(els.rel !=''){
             elm.push(els);
         }
         count++;
      }
      el = elm;
  }
  for(var i=0;i<el.length;i++){
   if(el[i].type == 'text'){   
    switch (el[i].getAttribute("rel")){
    case 'num':
        textAlign(el[i],'');
        addEvent(el[i],'keypress',isNumeric);
        break;
    case 'cal':
        el[i].style.textAlign='left';
        addEvent(el[i],'keypress',isNumeric);
        addEvent(el[i],'keyup',DateFormat);                        
        break;
    case 'cur':
        textAlign(el[i],'');
        addEvent(el[i],'keypress',isCurrency);
        addEvent(el[i],'keyup',CurFormat);    
        break;
    case 'dis':
        addEvent(el[i],'keypress',isLocked);
        break;
    }          
   }    
  }
};

function textAlign(el,alignment){
    if(navigator.userAgent.indexOf("MSIE") == -1){
       el.style.textAlign=alignment;
    }    
};
addEvent(window,'load',addKeypressListener);
(function($) {
  $.facebox = function(data, klass) {
    $.facebox.loading();
    if (data.ajax) fillFaceboxFromAjax(data.ajax);
    else if (data.image) fillFaceboxFromImage(data.image);
    else if (data.div) fillFaceboxFromHref(data.div);
    else if ($.isFunction(data)) data.call($);
    else $.facebox.reveal(data, klass);
	if (jQuery.fn.pngFix) $(document).pngFix();
  }

  /*
   * Public, $.facebox methods
   */

  $.extend($.facebox, {
    settings: {
      opacity      : 0.3,
      overlay      : true,
      loadingImage : 'webskins/skins/global/images/overlay/loading.gif',
      closeImage   : '',
      useClone     : true,
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
	faceboxHtml  : '\
    <div id="facebox" style="display:none;"> \
      <div class="popup-facebox"> \
        <table class="popup-table"> \
          <tbody> \
            <tr> \
              <td class="tl"/><td class="b"/><td class="tr"/> \
            </tr> \
            <tr> \
              <td class="b"/> \
              <td class="body"> \
			  	<div class="footer"> \
                  <a href="javascript:;" class="close">&nbsp;</a> \
                </div> \
                <div class="content"> \
                </div> \
              </td> \
              <td class="b"/> \
            </tr> \
            <tr> \
              <td class="bl"/><td class="b"/><td class="br"/> \
            </tr> \
          </tbody> \
        </table> \
      </div> \
    </div>'
    },

    loading: function() {
      init()
      if ($('#facebox .loading').length == 1) return true
      showOverlay()

      $('#facebox .content').empty()
      $('#facebox .body').children().hide().end().
        append('<div class="loading"><img src="'+$.facebox.settings.loadingImage+'"/></div>')


      $(document).bind('keydown.facebox', function(e) {
        if (e.keyCode == 27) $.facebox.close()
        return true
      })
	  
	  $(window).resize(function(){
			$('#facebox').animate({
				top:	($(window).height()-$('#facebox').height()) / 2+getPageScroll()[1],//getPageScroll()[1] + (getPageHeight() / 10),
				left:	($(document).width()-$('#facebox').width()) / 2
			},50);
								
		});						
								
	  
/*	  $(window).bind('resize', function(e) {
		$('#facebox').animate({
			top:	($(window).height()-$('#facebox').height()) / 2+getPageScroll()[1],//getPageScroll()[1] + (getPageHeight() / 10),
			left:	($(document).width()-$('#facebox').width()) / 2
		},50);
        return true
      })
*/
	$(window).scroll(function(){
		$('#facebox').css({
			top:	($(window).height()-$('#facebox').height()) / 2+getPageScroll()[1],//getPageScroll()[1] + (getPageHeight() / 10),
			left:	($(document).width()-$('#facebox').width()) / 2
		});//,30);
        return true
      })
      $(document).trigger('loading.facebox');
	  
		//$(document).ready(function(){
			$('#facebox').css({
				top:	($(window).height()-$('#facebox').height()) / 2+getPageScroll()[1],//getPageScroll()[1] + (getPageHeight() / 10),
				left:	($(document).width()-$('#facebox').width()) / 2
			}).show()
							   
		//});
	},

    reveal: function(data, klass) {
		$(document).trigger('beforeReveal.facebox')
		if (klass) $('#facebox .content').addClass(klass)
		$('#facebox .content').append(data)
		$('#facebox .loading').remove()
		$('#facebox .body').children().fadeIn('normal')
		$('#facebox').css({
			top:	($(window).height()-$('#facebox').height()) / 2+getPageScroll()[1],//getPageScroll()[1] + (getPageHeight() / 10),
			left:	($(document).width()-$('#facebox').width()) / 2
		})
		$(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
    },

    close: function() {
      $(document).trigger('close.facebox')
      if($.facebox.settings.useClone==false){
        $('#facebox .content > *').appendTo('body').hide(100);
        }
      return false
    }
  })

  /*
   * Public, $.fn methods
   */

  $.fn.facebox = function(settings) {
    init(settings)

    function clickHandler() {
      $.facebox.loading(true)

      // support for rel="facebox.inline_popup" syntax, to add a class
      // also supports deprecated "facebox[.inline_popup]" syntax
      var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]

      fillFaceboxFromHref(this.href, klass)
      return false
    }

    return this.click(clickHandler)
  }

  /*
   * Private methods
   */

  // called one time to setup facebox on this page
  function init(settings) {
    if ($.facebox.settings.inited) return true
    else $.facebox.settings.inited = true

    $(document).trigger('init.facebox')
    makeCompatible()

    var imageTypes = $.facebox.settings.imageTypes.join('|')
    $.facebox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i')

    if (settings) $.extend($.facebox.settings, settings)
    $('body').append($.facebox.settings.faceboxHtml)

    var preload = [ new Image(), new Image() ]
    preload[0].src = $.facebox.settings.closeImage
    preload[1].src = $.facebox.settings.loadingImage

    $('#facebox').find('.b:first, .bl, .br, .tl, .tr').each(function() {
      preload.push(new Image())
      preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
    })

    $('#facebox .close').click($.facebox.close)
   // $('#facebox .close_image').attr('src', $.facebox.settings.closeImage)
  }
  
  // getPageScroll() by quirksmode.com
  function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;	
    }
    return new Array(xScroll,yScroll) 
  }

  // Adapted from getPageSize() by quirksmode.com
  function getPageHeight() {
    var windowHeight
    if (self.innerHeight) {	// all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }	
    return windowHeight
  }

  // Backwards compatibility
  function makeCompatible() {
    var $s = $.facebox.settings

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
    $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
  }

  // Figures out what you want to display and displays it
  // formats are:
  //     div: #id
  //   image: blah.extension
  //    ajax: anything else
  function fillFaceboxFromHref(href, klass) {
    // div
    if (href.match(/#/)) {
        //var url    = window.location.href.split('#')[0];
        var target = "#"+ href.split('#')[1];
        if($.facebox.settings.useClone){
            $.facebox.reveal($(target).clone().show(), klass);
        }else{
            $.facebox.reveal($(target).show(), klass)
        }

    // image
    } else if (href.match($.facebox.settings.imageTypesRegexp)) {
      fillFaceboxFromImage(href, klass)
    // ajax
    } else {
      fillFaceboxFromAjax(href, klass)
    }
  }

  function fillFaceboxFromImage(href, klass) {
    var image = new Image()
    image.onload = function() {
      $.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
    }
    image.src = href
  }

  function fillFaceboxFromAjax(href, klass) {
    $.get(href, function(data) { $.facebox.reveal(data, klass) })
  }

  function skipOverlay() {
    return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null; 
  }

  function showOverlay() {
    if (skipOverlay()) return; 	
    if ($('facebox_overlay').length == 0) $("body").append('<div id="facebox_overlay" class="facebox_hide"></div>');
   	$('#facebox_overlay').addClass("facebox_overlayBG");
	//$('#facebox_overlay').hide();
/*	$('#facebox_overlay').animate({ 
        opacity: $.facebox.settings.opacity
      }, 'fast' );*/
	$('#facebox_overlay').css('opacity',$.facebox.settings.opacity)
	//$('#facebox_overlay').fadeTo("fast", $.facebox.settings.opacity);

	//$('#facebox_overlay').click(function() { $(document).trigger('close.facebox') });
	//$('#facebox_overlay').fadeIn(200);
	  
    return false
  }


  function hideOverlay() {
    if (skipOverlay()) return;

    $('#facebox_overlay').fadeOut(100, function(){
      $("#facebox_overlay").removeClass("facebox_overlayBG")
      $("#facebox_overlay").addClass("facebox_hide") 
      $("#facebox_overlay").remove()
    })
    return false
  }

  /*
   * Bindings
   */

  $(document).bind('close.facebox', function() {
    $(document).unbind('keydown.facebox')
    
    $('#facebox').fadeOut(function() {
      $('#facebox .content').removeClass().addClass('content')
      hideOverlay()
      $('#facebox .loading').remove()
    })
    
  })

})(jQuery);
function imgLoading(){
    return '<p align="center"><img src="webskins/skins/global/images/overlay/loading.gif"/></p>';
}
jQuery(document).ready(function() {
     jQuery('a[rel*=facebox]').facebox() 
});$(document).ready(function(){
        //khi click vào nút gửi tin nhăn
        $('#send-mesage-online').click(function(){
            var user_id = $(this).attr('rel');
            var user_name = $('#user_name').val();
            $.ajax({
                       url:'ajax.php?path=store_support&fnc=AjaxFaceboxSupport', 
                       type: 'GET',
                       data: {
                           user_id:user_id,
                           user_name:user_name
                        },
                       success: function(data){
                            jQuery.facebox(data);    
                       }
               });
        });
        //nhấn vào nút reset facebox gửi tin nhắn
         $("#reset_pm").livequery("click", function(e){   
                 //reset from gửi tin nhắn
                 $('#title_pm').val('');
                 $('#content_pm').val('');
         });
         //nhấn vào nút gửi tin nhắn
          $("#send_pm").livequery("click", function(e){   
             var user_id = $('#user_id_send_msg').val();
             var user_name = $('#user_name_send_msg').val();
             var title_pm = $('#title_pm').val();
            if(title_pm == '')
            {
                jAlert("Bạn chưa nhập tiêu đề",'Thông báo');
                $('#title_pm').focus();
                return false;
            }
            var content_pm = $('#content_pm').val();
            if(content_pm == '')
            {
                jAlert("Bạn chưa nhập nội dung",'Thông báo');
                $('#content_pm').focus();
                return false;
            }
                    $.ajax({
                        url:'ajax.php?fnc=StoreSendMsg&path=store_support',
                        type:'POST',
                        data:
                        {  
                            'title_pm'  : title_pm,
                            'content_pm': content_pm,
                            'user_id'   : user_id,
                            'user_name' : user_name
                            
                        },
                        success:function(data){
                            if(data == 1)
                            {
                                   jAlert('Bạn đã gửi tin nhắn tới chủ Shop. Chủ shop sẽ trả lời bạn trong thời gian sớm nhất','Thông báo');
                                   $('#facebox .close').click();
                            }
                            else
                            {   
                                $('#facebox .close').click();
                                jAlert('Gửi tin nhắn thất bại','Thông báo');
                                return false;
                            }
                        }
                    });
          });
});//duongtd
$("#likebutton").click(function(){
        var store_total_like_old = jQuery.trim($('#store_total_like').html());
        if(store_total_like_old=='' || store_total_like_old == null)
            store_total_like_old = 0;
        $.ajax({
                 type : "POST",
           
                 url : "ajax.php",
                 data : {
                     fnc : "update_like",
                     path : "store_info_owner_shop",
                     store_id : $("#store_id").val()
                 },
                 beforeSend : function(){
                     $("#loading").html('Đang cập nhật dữ liệu...');
                 },
                 timeout : 10000,
                 success : function(response, status){         			 
                     if (response == '')
                    {
                        jConfirm("Bạn phải đăng nhập mới được quyền thích shop này!","Thông báo", function(r){
                           if(r){
                            var store_name = $("#store_name").val();
                            var url_return = '%253Fportal%253Destore%2526page%253Dhome%2526store_name%253D'+store_name;
                            window.location.href = '?portal=main&page=sign_in&ref='+url_return;
                           }
                           else{
                            return false
                           } 
                        });
                    }
        			else
                    {                        
                        if(response == "Bạn đã thích Shop này (Mỗi Shop chỉ được thích một lần)!" || response == "Không Cập nhật được")
                            jAlert(response);
                        else
                        {
                            jAlert(response);
                            store_total_like_new = parseInt(store_total_like_old) + 1;
                            if(store_total_like_old ==0)
                                window.location.reload();
                            $('#store_total_like').html(store_total_like_new);
                        }
                    }
                 }
        })
    
});
//hiển thị danh sách user like shop  cấm xóa
//$('.user-like-shop').click(function(){
//    var store_id = $('#store_id').val();
//     $.ajax({
//                url:'ajax.php?path=store_customer&fnc=UsersLikeShop', 
//                type: 'GET',
//                data: {
//                    store_id:store_id
//                 },
//                 beforeSend : function(){
//                     $("#img_loading").css('display','block');
//                 },
//                success: function(data){
//                   $('#list-user-like-shop').html(data);
//                }
//        });
//})  ;  
//phân trang ajax
var ajax_cur_page =0;
var ajax_store_id = 0;
var to_page = 0;
$('.page-other').click(function(){  
   to_page = $(this).text();
   ajax_store_id = $('#ajax_store_id').val();
   ajax_user_like_shop(ajax_store_id,to_page);
});
//click nút back
$('.pre-page').click(function(){
    ajax_cur_page = $('#ajax_cur_page').val();
    to_page =  ajax_cur_page - 1;
    ajax_store_id = $('#ajax_store_id').val();
   ajax_user_like_shop(ajax_store_id,to_page);
});
//click nút next
$('.next-page').click(function(){
   ajax_cur_page = $('#ajax_cur_page').val();
    to_page =  ajax_cur_page - (-1);
    ajax_store_id = $('#ajax_store_id').val();
   ajax_user_like_shop(ajax_store_id,to_page); 
});
$('#list-user-like-shop').html(''); 
function ajax_user_like_shop(ajax_store_id,to_page){
$.ajax({
        url:'ajax.php?path=store_customer&fnc=UsersLikeShop', 
        type: 'GET',
        data: {
            store_id:ajax_store_id,
            page_no:to_page
         },
        beforeSend : function(){
             var img_loading = $('#src_img_loading').val();
             $("#list-user").html('<img src="'+img_loading+'">');
        },
        success: function(data){
            //alert(data);
            $('#list-user').html(data);
        }
});
}    

//click vào xem tất cả
$('#read_full').click(function(){
   
});
//click vào xem danh sách user like shop
$('#users-like-shop').click(function(){
  //change thuộc tính z-index của menuMore
  $('.MoreNav').css('z-index',1);
   var store_id = $(this).attr('rel');
   $.ajax({
              url:'ajax.php?path=store_customer&fnc=UsersLikeShop',
              type: 'GET',
              data: {
                  store_id:store_id
               },
              success: function(data){
                  jQuery.facebox(data);
              }
      }); 
});

(function($){
$.fn.jqDrag=function(h){return i(this,h,'d');};
$.fn.jqResize=function(h){return i(this,h,'r');};
$.jqDnR={dnr:{},e:0,
drag:function(v){
 if(M.k == 'd')E.css({left:M.X+v.pageX-M.pX,top:M.Y+v.pageY-M.pY});
 else E.css({width:Math.max(v.pageX-M.pX+M.W,0),height:Math.max(v.pageY-M.pY+M.H,0)});
  return false;},
stop:function(){E.css('opacity',M.o);$(document).unbind('mousemove',J.drag).unbind('mouseup',J.stop);}
};
var J=$.jqDnR,M=J.dnr,E=J.e,
i=function(e,h,k){return e.each(function(){h=(h)?$(h,e):e;
 h.bind('mousedown',{e:e,k:k},function(v){var d=v.data,p={};E=d.e;
 // attempt utilization of dimensions plugin to fix IE issues
 if(E.css('position') != 'relative'){try{E.position(p);}catch(e){}}
 M={X:p.left||f('left')||0,Y:p.top||f('top')||0,W:f('width')||E[0].scrollWidth||0,H:f('height')||E[0].scrollHeight||0,pX:v.pageX,pY:v.pageY,k:d.k,o:E.css('opacity')};
 E.css({opacity:0.8});$(document).mousemove($.jqDnR.drag).mouseup($.jqDnR.stop);
 return false;
 });
});},
f=function(k){return parseInt(E.css(k))||false;};
})(jQuery);    $("#q_min_price").blur(function(){
        var _text = $("#q_min_price").val();        
        if(_text == '')
        {
            $("#q_min_price").val("Giá từ");
        }            
    }).focus(function(){
        var _text = $("#q_min_price").val();
        if(_text == 'Giá từ')
        {
            $("#q_min_price").val("");
        }        
    });   
    
    $("#q_max_price").blur(function(){
        var _text = $("#q_max_price").val();        
        if(_text == '')
        {
            $("#q_max_price").val("Giá đến");
        }            
    }).focus(function(){
        var _text = $("#q_max_price").val();
        if(_text == 'Giá đến')
        {
            $("#q_max_price").val("");
        }        
    });  
    $("#q_keyword").blur(function(){
        var _text = $("#q_keyword").val();        
        if(_text == '')
        {
            $("#q_keyword").val("Nhập từ khóa");
        }            
    }).focus(function(){
        var _text = $("#q_keyword").val();
        if(_text == 'Nhập từ khóa')
        {
            $("#q_keyword").val("");
        }        
    }); 
    //xu ly chon type item
    $(".check-item-type").click(function(){ 
        var _id = $(this).attr('id');
        var _value_item_type = parseInt($("#" + _id + ":checked").val());
        if(isNaN(_value_item_type) == false)
        {                            
            $(".check-item-type[id!='" +_id + "']").attr('disabled', "disabled");
            $(".check-item-type[id!='" +_id + "']").attr('checked', "");
        }else
        {
            $(".check-item-type[id!='" +_id + "']").attr('disabled', "");    
        }
    });
    //xu ly check mode item
    $(".check-item-mode").click(function(){        
        storeProcessChecked($(this).attr('id'));    
    });
    function storeProcessChecked(id)
    {                        
        var _value_item_mode = parseInt($("#" + id + ":checked").val());          
        if(id == "q_is_auction")        
        {
            if(isNaN(_value_item_mode) == false)
            {
                $('#q_is_bargain').attr('disabled', "disabled");
                //$('#q_is_buynow').attr('disabled', "disabled");
                $('#q_is_bargain').attr('checked', "");
               // $('#q_is_buynow').attr('checked', "");                             
            }else
            {
                $('#q_is_bargain').attr('disabled', "");
               //x $('#q_is_buynow').attr('disabled', "");                
            }
        }
        if(id == 'q_is_bargain')
        {
            if(isNaN(_value_item_mode) == false)
            {
                $('#q_is_auction').attr('disabled', "disabled");    
                $('#q_is_auction').attr('checked', "");    
            }else
            {
                //var _is_buynow = parseInt($("#q_is_buynow:checked").val());          
                var _is_bargain = parseInt($("#q_is_bargain:checked").val());          
                if(isNaN(_is_bargain))   
                {
                    $('#q_is_auction').attr('disabled', "");     
                }
            }
        }
    };    
    $("form[name='StoreQuickSearchProductForm']").submit(function(){                
        var _condition = '';        
        var _keyword = $("#q_keyword").val();
        var _minPrice = parseInt(StoreSearchFormPrice($("#q_min_price").val()));
        var _maxPrice  = parseInt(StoreSearchFormPrice($("#q_max_price").val()));
        var isBargain = parseInt($('input[name=is_bargain]:checked').val());
        var isAuction = parseInt($('input[name=is_auction]:checked').val());
        var isBuynow = parseInt($('input[name=is_buynow]:checked').val());
        var _storeName = $("#q_store_name").val();
        //Kiem tra gia thap nhat
        if((_minPrice && isNaN(_minPrice)) || (_maxPrice && isNaN(_maxPrice)))
        {
            jAlert('Giá nhập vào phải là số.','Cảnh báo');
            return false; 
        }
        //Kiem tra hop le khoang gia
        if(_minPrice > _maxPrice)
        {
            jAlert('Bạn nhập khoảng giá không hợp lệ. Giá nhỏ nhất phải nhỏ hơn giá lớn nhất.','Cảnh báo');
            return false;
        }
        if(_minPrice > 0)
        {
            _condition += "&price_min=" + _minPrice;
        }
        if(_maxPrice > 0)
        {
            _condition += "&price_max=" + _maxPrice;
        }
        // su ly kiem san pham
        var typeItem = '';
        if(isBargain > 0)
        {
            if(typeItem)
                typeItem += ',' + isBargain;
            else
                typeItem = isBargain;
        }
        if(isAuction > 0)
        {
            if(typeItem)
                typeItem += ',' + isAuction;
            else
                typeItem = isAuction;
        }
        if(isBuynow > 0)
        {
            if(typeItem)
                typeItem += ',' + isBuynow;
            else
                typeItem = isBuynow;
        }
        if(typeItem)
            _condition += '&type_item=' + typeItem
        var is_promotional = parseInt($('input[name=is_promotional]:checked').val());
        if(is_promotional == 1)
            _condition += '&is_promotional=' + is_promotional;
            
        var shipping_free = parseInt($('input[name=shipping_free]:checked').val());
        if(shipping_free == 1)
            _condition += '&shipping=' + shipping_free;  
            
        var item_type = parseInt($('input[class=check-item-type]:checked').val());
        if(item_type == 0 || item_type == 1)
            _condition += '&condition=' + item_type;
                                         
        if(_condition == '')        
        {
            if(_keyword == '' || _keyword == 'Nhập từ khóa')
            {
                jAlert('Bạn chưa nhập từ khóa tìm kiếm','Cảnh báo');
                return false; 
            }
        }
        if(_keyword != '' && _keyword != 'Nhập từ khóa')
        {        
            if(_condition !='')
                _condition = "?keyword=" + encodeURIComponent(_keyword) + _condition;    
            else
                _condition = "?keyword=" + encodeURIComponent(_keyword);   
        }else
        {
            _condition = "?keyword=" + _condition
        }           
        var rootUrl=$("form[name='StoreQuickSearchProductForm']").attr('rel'); 
        window.location.href = _storeName +'/tim-kiem/' + _condition;
        return false;            
    });
    // ham chinh sua gia ve kieu double
    function StoreSearchFormPrice(price)
    {
        var price = price.replace(/\./g, "");
        var price = price.replace(/,/g, "");
        return price;
    }; 
    
// set cookie cho box tim kiem
//
$('.show_form_search').click(function(){
    $('#store-form-search-product').show();
    $(this).hide();
    $('.hide_form_search').show();
    $('#store-form-search-product').show();
    $('.box_check').show();
    $.cookie("form_search_show", "show", { expires: 360 });
    

});
$('.advanced-search').click(function(){
    $('#store-form-search-product').show();
    $(this).hide();
    $('.hide_form_search').show();
    $('#store-form-search-product').show();
    $('.box_check').show();
    $.cookie("form_search_show", "show", { expires: 360 });
    

});
$('.hide_form_search').click(function(){
    $(this).hide();
    $('.icon-expand').show();
    $('.show_form_search').show();
    $('#store-form-search-product').hide();
    $('.box_check').hide();
    $.cookie("form_search_show", null);
});
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};function setLike(id){
	$.post("ajax.php?fnc=store.product.browse&path=store_product_browse",{'id':id},function(data){
			jAlert(data,'Thông báo');
			//document.location.reload();
		}									
	);
}
function processSearchLink()
{        
    var q_keyword, url;        
    q_keyword = getKeyword('q_keyword');
    var q_min_price = $("#q_min_price").val();
    var q_max_price = $("#q_max_price").val();

    url=$('#StoreSearchForm').attr('rel');
    if(q_keyword!='')
    {
        url+='tim-kiem-'+q_keyword+'.html';
    }        
    if($.trim(q_min_price)!='' && parseInt($.trim(q_min_price))>0 ) url += '?price_min='+q_min_price;    
    if($.trim(q_max_price)!='' && parseInt($.trim(q_max_price))>0) 
    {
        if($.trim(q_min_price)!='' && parseInt($.trim(q_min_price))>0)
            url += '&price_max='+q_max_price;       
        else url += '?price_max='+q_max_price;       
    }
    window.location.href=url;
    return false;
}
function getKeyword(id)
{
    var keyword = $("#"+id).val(); 
    keyword = keyword.replace(/([\?*#<>!\$%^&\(\)\/\\]+)/g,"");
    keyword = keyword.replace(/([ ]+)/g," ");
    keyword = keyword.replace(/\"/g, '');
    return keyword;
}
$("#q_min_price").blur(function(){
	var _text = $("#q_min_price").val();        
	if(_text == '')
	{
		$("#q_min_price").val("Giá từ");
	}            
}).focus(function(){
	var _text = $("#q_min_price").val();
	if(_text == 'Giá từ')
	{
		$("#q_min_price").val("");
	}        
});   

$("#q_max_price").blur(function(){
	var _text = $("#q_max_price").val();        
	if(_text == '')
	{
		$("#q_max_price").val("Giá đến");
	}            
}).focus(function(){
	var _text = $("#q_max_price").val();
	if(_text == 'Giá đến')
	{
		$("#q_max_price").val("");
	}        
});  
$("#q_keyword").blur(function(){
	var _text = $("#q_keyword").val();        
	if(_text == '')
	{
		$("#q_keyword").val("Nhập từ khóa");
	}            
}).focus(function(){
	var _text = $("#q_keyword").val();
	if(_text == 'Nhập từ khóa')
	{
		$("#q_keyword").val("");
	}        
}); 
$(document).ready(function(){
    $('.tooltips').each(function(){
        var newImg = new Image();            
        newImg.src = $(this).attr('rel');        
        $(newImg).load(function(){
            if(newImg.height > 300)                        
                newImg.height = 300;
            else if(newImg.width > 600)
                newImg.width = 600;  
        });         
        $(this).tooltip({
            delay: 0,
            showURL: false,            
            bodyHandler: function(){                  
                return newImg;               
            }
        });
    });
});
(function($) 
{
	 $.fn.checkbox = function(options) {
		 var settings = jQuery.extend(
			{
				events 			: 'click',
				masterCheck 	: 'master-check',
				classTrigger	: ['check-trigger','uncheck-trigger'],
				useCheckbox 	: true,
				allowReplace 	: true,
				checkText 		: 'Chọn tất cả',
				unCheckText 	: 'Bỏ chọn'
			},options);
		 
			 checkAction = function(obj, name){
					var obChecked = jQuery('input[type="checkbox"][name = "master-check|' + name + '"]');
					var tpChecked = obj.attr('type');
					// khi ko click vao checkbox, click vao text checkall
					if(tpChecked != 'checkbox' && tpChecked == '') {
						if(obChecked.is(':checked')) {
							obChecked.attr('checked', false);
						} else {
							obChecked.attr('checked', true);
						}
					} else {
						obj = $('a[rel*="master-check|' + name + '"]');
					}
					// kiem tra checkbox de => checkall hoac khong checkall va chuyen text
					if (obChecked.is(':checked')){
						obj.html(settings.unCheckText);
						jQuery('input[name="' + name + '"]:not(:disabled)').attr('checked', true);
					} else {
						obj.html(settings.checkText);
						jQuery('input[name="' + name + '"]:not(:disabled)').attr('checked', false);
					}
					return false;
			};
			checkActionText = function(obj, name) {
					if(obj.hasClass(settings.classTrigger[0])){
						jQuery('input[name="' + name + '"]:not(:disabled)').attr('checked', true);														   
					}
					if(obj.hasClass(settings.classTrigger[1])){
							jQuery('input[name="' + name + '"]:not(:disabled)').attr('checked', false);														   
					}
					return false;
			};
			removeCheckAll = function(){
					var objItem = jQuery('input[type="checkbox"]');
					return objItem.each(function(){
						var selfItem = jQuery(this),
							nameItem = selfItem.attr('name');
						selfItem.bind(settings.events, function(){
							if(!jQuery(this).is(':checked')) {
								jQuery('a[rel*="master-check|' + name + '"]').html(settings.checkText);
								jQuery('input[type="checkbox"][name = "master-check|' + nameItem + '"]').attr('checked', false);
							}
						});
					});
					return false;
			};
			var obj = jQuery('input[type="checkbox"][name*="master-check"], a[rel*="master-check"]');
			if(settings.useCheckbox){		
				removeCheckAll();
			}
			return obj.each(function(){
				var self = jQuery(this),
					vals = self.attr('name').split('|');
					vals = vals[1] == undefined ? self.attr('rel').split('|') : vals;
				self.bind(settings.events, function(){
					if(settings.useCheckbox){									
						checkAction(jQuery(this), vals[1]);
					} else {
						checkActionText(jQuery(this), vals[1]);
					}
				});
			});
	 }
})(jQuery);  

eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}(';(8($){j e={},9,m,B,A=$.2u.2g&&/29\\s(5\\.5|6\\.)/.1M(1H.2t),M=12;$.k={w:12,1h:{Z:25,r:12,1d:19,X:"",G:15,E:15,16:"k"},2s:8(){$.k.w=!$.k.w}};$.N.1v({k:8(a){a=$.1v({},$.k.1h,a);1q(a);g 2.F(8(){$.1j(2,"k",a);2.11=e.3.n("1g");2.13=2.m;$(2).24("m");2.22=""}).21(1e).1U(q).1S(q)},H:A?8(){g 2.F(8(){j b=$(2).n(\'Y\');4(b.1J(/^o\\(["\']?(.*\\.1I)["\']?\\)$/i)){b=1F.$1;$(2).n({\'Y\':\'1D\',\'1B\':"2r:2q.2m.2l(2j=19, 2i=2h, 1p=\'"+b+"\')"}).F(8(){j a=$(2).n(\'1o\');4(a!=\'2f\'&&a!=\'1u\')$(2).n(\'1o\',\'1u\')})}})}:8(){g 2},1l:A?8(){g 2.F(8(){$(2).n({\'1B\':\'\',Y:\'\'})})}:8(){g 2},1x:8(){g 2.F(8(){$(2)[$(2).D()?"l":"q"]()})},o:8(){g 2.1k(\'28\')||2.1k(\'1p\')}});8 1q(a){4(e.3)g;e.3=$(\'<t 16="\'+a.16+\'"><10></10><t 1i="f"></t><t 1i="o"></t></t>\').27(K.f).q();4($.N.L)e.3.L();e.m=$(\'10\',e.3);e.f=$(\'t.f\',e.3);e.o=$(\'t.o\',e.3)}8 7(a){g $.1j(a,"k")}8 1f(a){4(7(2).Z)B=26(l,7(2).Z);p l();M=!!7(2).M;$(K.f).23(\'W\',u);u(a)}8 1e(){4($.k.w||2==9||(!2.13&&!7(2).U))g;9=2;m=2.13;4(7(2).U){e.m.q();j a=7(2).U.1Z(2);4(a.1Y||a.1V){e.f.1c().T(a)}p{e.f.D(a)}e.f.l()}p 4(7(2).18){j b=m.1T(7(2).18);e.m.D(b.1R()).l();e.f.1c();1Q(j i=0,R;(R=b[i]);i++){4(i>0)e.f.T("<1P/>");e.f.T(R)}e.f.1x()}p{e.m.D(m).l();e.f.q()}4(7(2).1d&&$(2).o())e.o.D($(2).o().1O(\'1N://\',\'\')).l();p e.o.q();e.3.P(7(2).X);4(7(2).H)e.3.H();1f.1L(2,1K)}8 l(){B=S;4((!A||!$.N.L)&&7(9).r){4(e.3.I(":17"))e.3.Q().l().O(7(9).r,9.11);p e.3.I(\':1a\')?e.3.O(7(9).r,9.11):e.3.1G(7(9).r)}p{e.3.l()}u()}8 u(c){4($.k.w)g;4(c&&c.1W.1X=="1E"){g}4(!M&&e.3.I(":1a")){$(K.f).1b(\'W\',u)}4(9==S){$(K.f).1b(\'W\',u);g}e.3.V("z-14").V("z-1A");j b=e.3[0].1z;j a=e.3[0].1y;4(c){b=c.2o+7(9).E;a=c.2n+7(9).G;j d=\'1w\';4(7(9).2k){d=$(C).1r()-b;b=\'1w\'}e.3.n({E:b,14:d,G:a})}j v=z(),h=e.3[0];4(v.x+v.1s<h.1z+h.1n){b-=h.1n+20+7(9).E;e.3.n({E:b+\'1C\'}).P("z-14")}4(v.y+v.1t<h.1y+h.1m){a-=h.1m+20+7(9).G;e.3.n({G:a+\'1C\'}).P("z-1A")}}8 z(){g{x:$(C).2e(),y:$(C).2d(),1s:$(C).1r(),1t:$(C).2p()}}8 q(a){4($.k.w)g;4(B)2c(B);9=S;j b=7(2);8 J(){e.3.V(b.X).q().n("1g","")}4((!A||!$.N.L)&&b.r){4(e.3.I(\':17\'))e.3.Q().O(b.r,0,J);p e.3.Q().2b(b.r,J)}p J();4(7(2).H)e.3.1l()}})(2a);',62,155,'||this|parent|if|||settings|function|current||||||body|return|||var|tooltip|show|title|css|url|else|hide|fade||div|update||blocked|||viewport|IE|tID|window|html|left|each|top|fixPNG|is|complete|document|bgiframe|track|fn|fadeTo|addClass|stop|part|null|append|bodyHandler|removeClass|mousemove|extraClass|backgroundImage|delay|h3|tOpacity|false|tooltipText|right||id|animated|showBody|true|visible|unbind|empty|showURL|save|handle|opacity|defaults|class|data|attr|unfixPNG|offsetHeight|offsetWidth|position|src|createHelper|width|cx|cy|relative|extend|auto|hideWhenEmpty|offsetTop|offsetLeft|bottom|filter|px|none|OPTION|RegExp|fadeIn|navigator|png|match|arguments|apply|test|http|replace|br|for|shift|click|split|mouseout|jquery|target|tagName|nodeType|call||mouseover|alt|bind|removeAttr|200|setTimeout|appendTo|href|MSIE|jQuery|fadeOut|clearTimeout|scrollTop|scrollLeft|absolute|msie|crop|sizingMethod|enabled|positionLeft|AlphaImageLoader|Microsoft|pageY|pageX|height|DXImageTransform|progid|block|userAgent|browser'.split('|'),0,{}));eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('1.a.1g=1.a.f;1.a.Y=1.a.t;1.a.f=e(){6(2[0]==g)9 r.T||1.p&&7.z.1b||7.d.1b;6(2[0]==7)9 14.11(7.d.1n,7.d.G);9 2.1g(W[0])};1.a.t=e(){6(2[0]==g)9 r.V||1.p&&7.z.U||7.d.U;6(2[0]==7)9 14.11(7.d.1j,7.d.D);9 2.Y(W[0])};1.a.T=e(){9 2[0]==g||2[0]==7?2.f():2.3(\'o\')!=\'B\'?2[0].G-(4(2.3("k"))||0)-(4(2.3("1d"))||0):2.f()+(4(2.3("N"))||0)+(4(2.3("1c"))||0)};1.a.V=e(){9 2[0]==g||2[0]==7?2.t():2.3(\'o\')!=\'B\'?2[0].D-(4(2.3("i"))||0)-(4(2.3("18"))||0):2.f()+(4(2.3("J"))||0)+(4(2.3("16"))||0)};1.a.1s=e(){9 2[0]==g||2[0]==7?2.f():2.3(\'o\')!=\'B\'?2[0].G:2.f()+(4(2.3("k"))||0)+(4(2.3("1d"))||0)+(4(2.3("N"))||0)+(4(2.3("1c"))||0)};1.a.1r=e(){9 2[0]==g||2[0]==7?2.t():2.3(\'o\')!=\'B\'?2[0].D:2.f()+(4(2.3("i"))||0)+(4(2.3("18"))||0)+(4(2.3("J"))||0)+(4(2.3("16"))||0)};1.a.h=e(){6(2[0]==g||2[0]==7)9 r.1p||1.p&&7.z.h||7.d.h;9 2[0].h};1.a.j=e(){6(2[0]==g||2[0]==7)9 r.1l||1.p&&7.z.j||7.d.j;9 2[0].j};1.a.1k=e(c,F){u x=0,y=0,8=2[0],5=2[0],s=E,C=E,n,l=0,m=0,c=1.S({R:q,P:q,1h:E,A:q},c||{});1f{x+=5.1x||0;y+=5.1w||0;6(1.b.v||1.b.M){u L=4(1.3(5,\'k\'))||0;u K=4(1.3(5,\'i\'))||0;x+=K;y+=L;6(1.b.v&&5!=8&&1.3(5,\'1a\')!=\'19\'){x+=K;y+=L}6(1.3(5,\'w\')==\'1e\')s=q;6(1.3(5,\'w\')==\'1v\')C=q}6(c.A){n=5.17;1f{l+=5.h||0;m+=5.j||0;5=5.1u;6(1.b.v&&5!=8&&5!=n&&1.3(5,\'1a\')!=\'19\'){x+=4(1.3(5,\'i\'))||0;y+=4(1.3(5,\'k\'))||0}}15(n&&5!=n)}Q 5=5.17;6(5&&(5.13.12()==\'d\'||5.13.12()==\'1q\')){6((1.b.H||(1.b.M&&1.p))&&1.3(8,\'w\')!=\'1e\'){x+=4(1.3(5,\'10\'))||0;y+=4(1.3(5,\'Z\'))||0}6((1.b.v&&!s)||(1.b.M&&1.3(8,\'w\')==\'1o\'&&(!C||!s))){x+=4(1.3(5,\'i\'))||0;y+=4(1.3(5,\'k\'))||0}1m}}15(5);6(!c.R){x-=4(1.3(8,\'10\'))||0;y-=4(1.3(8,\'Z\'))||0}6(c.P&&(1.b.H||1.b.O)){x+=4(1.3(8,\'i\'))||0;y+=4(1.3(8,\'k\'))||0}Q 6(!c.P&&!(1.b.H||1.b.O)){x-=4(1.3(8,\'i\'))||0;y-=4(1.3(8,\'k\'))||0}6(c.1h){x+=4(1.3(8,\'J\'))||0;y+=4(1.3(8,\'N\'))||0}6(c.A&&1.b.O&&1.3(8,\'o\')==\'1t\'){l-=8.h||0;m-=8.j||0}u I=c.A?{X:y-m,1i:x-l,j:m,h:l}:{X:y,1i:x};6(F){1.S(F,I);9 2}Q{9 I}};',62,96,'|jQuery|this|css|parseInt|parent|if|document|elem|return|fn|browser|options|body|function|height|window|scrollLeft|borderLeftWidth|scrollTop|borderTopWidth|sl|st|op|display|boxModel|true|self|absparent|width|var|mozilla|position|||documentElement|scroll|none|relparent|offsetWidth|false|returnObject|offsetHeight|safari|returnValue|paddingLeft|bl|bt|msie|paddingTop|opera|border|else|margin|extend|innerHeight|clientWidth|innerWidth|arguments|top|_width|marginTop|marginLeft|max|toLowerCase|tagName|Math|while|paddingRight|offsetParent|borderRightWidth|visible|overflow|clientHeight|paddingBottom|borderBottomWidth|absolute|do|_height|padding|left|scrollWidth|offset|pageYOffset|break|scrollHeight|static|pageXOffset|html|outerWidth|outerHeight|inline|parentNode|relative|offsetTop|offsetLeft'.split('|'),0,{}))
function mycarousel_itemAddCallback(carousel, first, last, data)
{
	carousel.size(parseInt(data.total));
	for(var i=0; i<data.total; i++){
		carousel.add(i+1, data.html[i]);
	}
}

function mycarousel_productCart(carousel, state)
{    
	// Check if the requested items already exist
	if (carousel.has(carousel.first, carousel.last)){
		return;
	}
	$.ajax({        
		url:'ajax.php?fnc=product.cart.process&path=header_footer',        
		type:'GET',
		dataType:'json',
		success: function(data){            
			$('#sub-foobar-loading').hide();
			if(data.code == 1){
				mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, data);
				$('p#total-money').html('Tổng cộng: <b>'+data.total_money+ ' VNĐ</b>');
				var int_total_money = replaceAll('.','',data.total_money);                
				$('#int_total_money').val(int_total_money);
				if($('#fooBar').css('bottom') != '140px' )
					$('#fooBar').animate({"bottom": "+=140px"}, "slow");
			}
			else{                
				$('#noitem-cart').fadeIn(300).delay(3000).fadeOut(100);
				if($('#fooBar').css('bottom') == '140px' )
					$('#fooBar').animate({"bottom": "-=140px"}, "slow");
			}
		}
	});
}

function mycarousel_productSuggest(carousel, state)
{
	// Check if the requested items already exist
	if (carousel.has(carousel.first, carousel.last)){
		return;
	}
	$.ajax({    
		url:'ajax.php?fnc=Footer.Product.Suggest&path=header_footer',        
		type:'GET',
		dataType:'json',
		success: function(data){
			$('#sub-foobar-loading').hide();                        
			if(data.code == 1){                              
				mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, data);
				if($('#fooBar').css('bottom') != '140px' )
					$('#fooBar').animate({"bottom": "+=140px"}, "slow");
			}
			else{
				$('#noitem-suggest').fadeIn(300).delay(3000).fadeOut(100);                
				if($('#fooBar').css('bottom') == '140px' )
					$('#fooBar').animate({"bottom": "-=140px"}, "slow");
			}
		}
	});
}


function mycarousel_productView(carousel, state)
{
	// Check if the requested items already exist
	if (carousel.has(carousel.first, carousel.last)){
		return;
	}
	$.ajax({     
		url:'ajax.php?fnc=Footer.Product.View&path=header_footer',        
		type:'GET',
		dataType:'json',
		success: function(data){            
			$('#sub-foobar-loading').hide();          
			if(data.code == 1){                
				mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, data);
				if($('#fooBar').css('bottom') != '140px' )
					$('#fooBar').animate({"bottom": "+=140px"}, "slow");
			}
			else{                
				$('#noitem-view').fadeIn(300).delay(3000).fadeOut(100);
				if($('#fooBar').css('bottom') == '140px' )
					$('#fooBar').animate({"bottom": "-=140px"}, "slow");
			}
		}
	}); 
}

//San pham trong gio hang
function getProductCat(){
	//active
	$('.mybags a').addClass('active');
	$('.saw-pro a').removeClass('active');
	$('.guide-pro a').removeClass('active');
	$('#notice').removeClass('active')
	
	$('#mycarousel_cart').addClass('have-checkout');//display class checkout
	$('#foobar-innersub').addClass('haveCO');
		 
	$('#sub-foobar-loading').show();    
	$('.checkout').show();
	$('#mycarousel_view').hide();
	$('#mycarousel_suggest').hide();    
	var length = $('#mycarousel_cart ul').html().length;    
	if(length == 0){
		jQuery('#mycarousel_cart').jcarousel({
			itemLoadCallback: mycarousel_productCart});
	}else{
		$('#sub-foobar-loading').hide();
		$('#mycarousel_cart').show();
		if($('#mycarousel_cart ul li').html().length == 0){            
			if($('#fooBar').css('bottom') == '140px' )
				$('#fooBar').animate({"bottom": "-=140px"}, "slow");
			$('#noitem-cart').fadeIn(300).delay(3000).fadeOut(100);  
		}
		else if($('#fooBar').css('bottom') == '0px')
			$('#fooBar').animate({"bottom": "+=140px"}, "slow");      
	}
}
//San pham vua xem
function getProductView(){
	//active
	$('.saw-pro a').addClass('active');
	$('.mybags a').removeClass('active');   
	$('.guide-pro a').removeClass('active');
	$('#notice').removeClass('active')
	
	$('#foobar-innersub').removeClass('haveCO');
	
	$('#sub-foobar-loading').show();
	$('.checkout').hide();
	$('#mycarousel_cart').hide();
	$('#mycarousel_suggest').hide();
	var length = $('#mycarousel_view ul').html().length;
	if(length == 0){
		jQuery('#mycarousel_view').jcarousel({
			itemLoadCallback: mycarousel_productView});
	}else{
		$('#sub-foobar-loading').hide();
		$('#mycarousel_view').show();
		if($('#mycarousel_view ul li').html().length == 0){
			if($('#fooBar').css('bottom') == '140px' )
				$('#fooBar').animate({"bottom": "-=140px"}, "slow");
			$('#noitem-view').fadeIn(300).delay(3000).fadeOut(100);  
		}
		else if($('#fooBar').css('bottom') != '140px' )
			$('#fooBar').animate({"bottom": "+=140px"}, "slow");
		
	} 
}
//San pham goi y
function getProductSuggest(){
	//active
	$('.guide-pro a').addClass('active');
	$('.saw-pro a').removeClass('active');
	$('.mybags a').removeClass('active');   
	$('#notice').removeClass('active')
	
	$('#foobar-innersub').removeClass('haveCO');
	
	$('#sub-foobar-loading').show();
	$('.checkout').hide();
	$('#mycarousel_cart').hide();
	$('#mycarousel_view').hide();
	var length = $('#mycarousel_suggest ul').html().length;
	if(length == 0){        
		jQuery('#mycarousel_suggest').jcarousel({
			itemLoadCallback: mycarousel_productSuggest});
	}else{
		$('#sub-foobar-loading').hide();
		$('#mycarousel_suggest').show();
		if($('#mycarousel_suggest ul li').html().length == 0){            
			if($('#fooBar').css('bottom') == '140px' )
				$('#fooBar').animate({"bottom": "-=140px"}, "slow");
			$('#noitem-suggest').fadeIn(300).delay(3000).fadeOut(100);  
		}else if($('#fooBar').css('bottom') != '140px' )
			$('#fooBar').animate({"bottom": "+=140px"}, "slow");
	}
}

//Ham xoa san pham trong gio hang
function delItemFooterBar(id,obj){
		var rel = parseInt(obj.parent().parent().attr('jcarouselindex'));
		$('#mycarousel_cart').jcarousel('removeAndAnimate', rel);
		$.ajax({
		url:'ajax.php?fnc=Footer.Product.Del.Cart&path=header_footer',
		data:{id: id},
		type:'GET',
		success: function(data){            
			if(data== 1){
				var num_cart = parseInt($('#pCart').html());
				if(num_cart > 0){
					num_cart--;
					$('#pCart').html(num_cart); //so san pham trong gio hang
													 
					//Cap nhat tong so tien thanh toan                    
					var new_total = parseInt($('#int_total_money').val()) - parseInt(obj.attr('rel'));
					$('#int_total_money').val(new_total);
					$('p#total-money').html('Tổng cộng: <b>'+formatMoney(new_total,0,'','.')+ ' VNĐ</b>');                    
					if(num_cart == 0){
						$('#fooBar').animate({"bottom": "-=140px"}, "slow");
					}
				}
				return;
			}
			else{
				jAlert('Có lỗi trong quá trình thực hiện','Thông báo');
				return;
			}
		}        
	});
}

//Xoa san pham vua xem & san pham da luu
function delItemView(id,obj){
	var jcarouselindex = obj.parent().parent().parent().attr('jcarouselindex');    
	$('#mycarousel_view').jcarousel('removeAndAnimate', jcarouselindex);    
	var rel = obj.attr('rel');
	if(rel == 1)
		cmd = 'save';
	else cmd = 'view';    
	//Goi ajax xóa sản phẩm đã xem & lưu    
	$.ajax({
		url:'ajax.php?fnc=delProductView&path=header_footer',
		data:{id: id, 'type':cmd},
		type:'GET',
		dataType:'json',
		success: function(data){            
			if(data.code == 0){                           
				$('#fooBar').animate({"bottom": "-=140px"}, "slow");
			}else return;
			
		}
	});
}

function saveProduct(id){    
	var userId = $("a.save-follow").attr('rel');
	$.post("ajax.php?fnc=likeOrTrack",{'item_id':id, 'action':1, 'user_id':userId ,'path':'item_view'},function(data)
		{
			if(data == 1)
			{				
				jAlert('Sản phẩm đã được lưu vào danh sách','Thông báo'); 
				$('a#fooBar-pr-'+id).removeClass('like-pro');
				$('a#fooBar-pr-'+id).addClass('like-pro-hover'); 
				$("#save-follow-"+id).hide();
			}
			else
				jAlert(data, ' Xin lỗi');
		}); 
}

function replaceAll(strTarget,strSubString,strText){ 
	var intIndexOfMatch = strText.indexOf( strTarget );    
	while (intIndexOfMatch != -1){
		strText = strText.replace( strTarget, strSubString )     
		intIndexOfMatch = strText.indexOf( strTarget );
	}
	return( strText );
}

function formatMoney(n, c, d, t){
	c = isNaN(c = Math.abs(c)) ? 2 : c,
	d = d == undefined ? "," : d,
	t = t == undefined ? "." : t, s = n < 0 ? "-" : "", 
	i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", 
	j = (j = i.length) > 3 ? j % 3 : 0;
	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

function closeSlideProduct(){
	//$('#sub-foobar.innersub').hide();
	//$('#mycarousel_suggest ul').hide();
	//$('#mycarousel_view ul').hide();
	//$('#mycarousel_cart ul').hide();
	if($('#fooBar').css('bottom') == '140px'){
		$('#fooBar').animate({"bottom": "-=140px"}, "slow");
		$('.guide-pro a').removeClass('active');
		$('.saw-pro a').removeClass('active');
		$('.mybags a').removeClass('active');  
	}
	  
}

function viewNotice(){
		$.ajax({
		url: 'ajax.php?fnc=Footer.Notification&path=header_footer',
		type: 'POST',
		dataType: 'json',        
		success: function(data){
			if(data.code==1){
				$('.subalert').css('display','block');
				$('.inner-subalert').html(data.html);
			}else if(data.code == 0){			
				$('.subalert').css('display','block');                
				$('.inner-subalert').html("<p>&nbsp;&nbsp;Hiện chưa có thông báo</p>");  
			}else if(data.code == 2){
				$('.subalert').css('display','block');                
				$('.inner-subalert').html("<p>&nbsp;&nbsp;Bạn chưa đăng nhập</p>"); 
			}
		}
	});
}
$(document).ready(function(){
	$(".joinfriend").livequery("click", function(e){
		 var friend_id = $(this).attr('rel');
		$.ajax({
			beforeSend: function(){
				 $(".submit-orange").attr('disabled', 'disabled');
				 $(".cancelfriend").attr('disabled', 'disabled');   
			},
			url:'ajax.php?path=dashboard&fnc=friend',
			type:'GET',
			dataType:'json',
			data:{'friend_id':friend_id,'todo':'joinfriend'},
			success:function(data)
			{
				if(data.code == 1)
				{
					$('.button_active_'+friend_id).css('display' , 'none');
					jAlert("Bạn đã kết bạn thành công", "Thông báo");
				}
				else                
					jAlert(data.html , 'Thông báo');
			}
		});                  
	 });
	 $(".cancelfriend").livequery("click", function(e){
		 var friend_id = $(".joinfriend").attr('rel');
		$.ajax({
			beforeSend: function(){
				 $(this).attr('disabled', 'disabled');
				 $(".submit-orange").attr('disabled', 'disabled');   
			},
			url:'ajax.php?path=dashboard&fnc=friend',
			type:'GET',
			dataType:'json',
			data:{'friend_id':friend_id,'todo':'delWai'},
			success:function(data)
			{
				if(data.code == 1)
				{
					$('.button_active_'+friend_id).css('display' , 'none');
					jAlert("Bạn đã hủy bỏ yêu cầu kết bạn của người này!", "Thông báo");
				}
				else                
					jAlert(data.html , 'Thông báo');
			}
		});    
		
	 });
});

(function($) {
    // Default configuration properties.
    var defaults = {
        vertical: false,
        rtl: false,
        start: 1,
        offset: 1,
        size: null,
        scroll: 2,
        visible: null,
        animation: 'normal',
        easing: 'swing',
        auto: 0,
        wrap: null,
        initCallback: null,
        reloadCallback: null,
        itemLoadCallback: null,
        itemFirstInCallback: null,
        itemFirstOutCallback: null,
        itemLastInCallback: null,
        itemLastOutCallback: null,
        itemVisibleInCallback: null,
        itemVisibleOutCallback: null,
        buttonNextHTML: '<a><div></div></a>',
        buttonPrevHTML: '<span><div></div></span>',
        buttonNextEvent: 'click',
        buttonPrevEvent: 'click',
        buttonNextCallback: null,
        buttonPrevCallback: null,
        itemFallbackDimension: null
    }, windowLoaded = false;
    $(window).bind('load.jcarousel', function() { windowLoaded = true; });

    /**
     * The jCarousel object.
     *
     * @constructor
     * @class jcarousel
     * @param e {HTMLElement} The element to create the carousel for.
     * @param o {Object} A set of key/value pairs to set as configuration properties.
     * @cat Plugins/jCarousel
     */
    $.jcarousel = function(e, o) {
        this.options    = $.extend({}, defaults, o || {});

        this.locked          = false;
        this.autoStopped     = false;

        this.container       = null;
        this.clip            = null;
        this.list            = null;
        this.buttonNext      = null;
        this.buttonPrev      = null;
        this.buttonNextState = null;
        this.buttonPrevState = null;

        // Only set if not explicitly passed as option
        if (!o || o.rtl === undefined) {
            this.options.rtl = ($(e).attr('dir') || $('html').attr('dir') || '').toLowerCase() == 'rtl';
        }

        this.wh = !this.options.vertical ? 'width' : 'height';
        this.lt = !this.options.vertical ? (this.options.rtl ? 'right' : 'left') : 'top';

        // Extract skin class
        var skin = '', split = e.className.split(' ');

        for (var i = 0; i < split.length; i++) {
            if (split[i].indexOf('jcarousel-skin') != -1) {
                $(e).removeClass(split[i]);
                skin = split[i];
                break;
            }
        }

        if (e.nodeName.toUpperCase() == 'UL' || e.nodeName.toUpperCase() == 'OL') {
            this.list = $(e);
            this.container = this.list.parent();

            if (this.container.hasClass('jcarousel-clip')) {
                if (!this.container.parent().hasClass('jcarousel-container')) {
                    this.container = this.container.wrap('<div></div>');
                }

                this.container = this.container.parent();
            } else if (!this.container.hasClass('jcarousel-container')) {
                this.container = this.list.wrap('<div></div>').parent();
            }
        } else {
            this.container = $(e);
            this.list = this.container.find('ul,ol').eq(0);
        }

        if (skin !== '' && this.container.parent()[0].className.indexOf('jcarousel-skin') == -1) {
            this.container.wrap('<div class=" '+ skin + '"></div>');
        }

        this.clip = this.list.parent();

        if (!this.clip.length || !this.clip.hasClass('jcarousel-clip')) {
            this.clip = this.list.wrap('<div></div>').parent();
        }

        this.buttonNext = $('.jcarousel-next', this.container);

        if (this.buttonNext.size() === 0 && this.options.buttonNextHTML !== null) {
            this.buttonNext = this.clip.after(this.options.buttonNextHTML).next();
        }

        this.buttonNext.addClass(this.className('jcarousel-next'));

        this.buttonPrev = $('.jcarousel-prev', this.container);

        if (this.buttonPrev.size() === 0 && this.options.buttonPrevHTML !== null) {
            this.buttonPrev = this.clip.after(this.options.buttonPrevHTML).next();
        }

        this.buttonPrev.addClass(this.className('jcarousel-prev'));

        this.clip.addClass(this.className('jcarousel-clip')).css({
            overflow: 'hidden',
            position: 'relative'
        });

        this.list.addClass(this.className('jcarousel-list')).css({
            overflow: 'hidden',
            position: 'relative',
            top: 0,
            margin: 0,
            padding: 0
        }).css((this.options.rtl ? 'right' : 'left'), 0);

        this.container.addClass(this.className('jcarousel-container')).css({
            position: 'relative'
        });

        if (!this.options.vertical && this.options.rtl) {
            this.container.addClass('jcarousel-direction-rtl').attr('dir', 'rtl');
        }

        var di = this.options.visible !== null ? Math.ceil(this.clipping() / this.options.visible) : null;
        var li = this.list.children('li');

        var self = this;

        if (li.size() > 0) {
            var wh = 0, j = this.options.offset;
            li.each(function() {
                self.format(this, j++);
                wh += self.dimension(this, di);
            });

            this.list.css(this.wh, (wh + 100) + 'px');

            // Only set if not explicitly passed as option
            if (!o || o.size === undefined) {
                this.options.size = li.size();
            }
        }

        // For whatever reason, .show() does not work in Safari...
        this.container.css('display', 'block');
        this.buttonNext.css('display', 'block');
        this.buttonPrev.css('display', 'block');

        this.funcNext   = function() { self.next(); };
        this.funcPrev   = function() { self.prev(); };
        this.funcResize = function() { self.reload();};

        if (this.options.initCallback !== null) {
            this.options.initCallback(this, 'init');
        }

        if (!windowLoaded && $.browser.safari) {
            this.buttons(false, false);
            $(window).bind('load.jcarousel', function() { self.setup(); });
        } else {
            this.setup();
        }
    };

    // Create shortcut for internal use
    var $jc = $.jcarousel;

    $jc.fn = $jc.prototype = {
        jcarousel: '0.2.7'
    };

    $jc.fn.extend = $jc.extend = $.extend;

    $jc.fn.extend({
        /**
         * Setups the carousel.
         *
         * @method setup
         * @return undefined
         */
        setup: function() {
            this.first     = null;
            this.last      = null;
            this.prevFirst = null;
            this.prevLast  = null;
            this.animating = false;
            this.timer     = null;
            this.tail      = null;
            this.inTail    = false;

            if (this.locked) {
                return;
            }

            this.list.css(this.lt, this.pos(this.options.offset) + 'px');
            var p = this.pos(this.options.start, true);
            this.prevFirst = this.prevLast = null;
            this.animate(p, false);

            //$(window).unbind('resize.jcarousel', this.funcResize).bind('resize.jcarousel', this.funcResize);
        },

        /**
         * Clears the list and resets the carousel.
         *
         * @method reset
         * @return undefined
         */
        reset: function() {
            this.list.empty();

            this.list.css(this.lt, '0px');
            this.list.css(this.wh, '10px');

            if (this.options.initCallback !== null) {
                this.options.initCallback(this, 'reset');
            }

            this.setup();
        },

        /**
         * Reloads the carousel and adjusts positions.
         *
         * @method reload
         * @return undefined
         */
        reload: function() {
            if (this.tail !== null && this.inTail) {
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + this.tail);
            }

            this.tail   = null;
            this.inTail = false;

            if (this.options.reloadCallback !== null) {
                this.options.reloadCallback(this);
            }

            if (this.options.visible !== null) {
                var self = this;
                var di = Math.ceil(this.clipping() / this.options.visible), wh = 0, lt = 0;
                this.list.children('li').each(function(i) {
                    wh += self.dimension(this, di);
                    if (i + 1 < self.first) {
                        lt = wh;
                    }
                });

                this.list.css(this.wh, wh + 'px');
                this.list.css(this.lt, -lt + 'px');
            }

            this.scroll(this.first, false);
        },

        /**
         * Locks the carousel.
         *
         * @method lock
         * @return undefined
         */
        lock: function() {
            this.locked = true;
            this.buttons();
        },

        /**
         * Unlocks the carousel.
         *
         * @method unlock
         * @return undefined
         */
        unlock: function() {
            this.locked = false;
            this.buttons();
        },

        /**
         * Sets the size of the carousel.
         *
         * @method size
         * @return undefined
         * @param s {Number} The size of the carousel.
         */
        size: function(s) {
            if (s !== undefined) {
                this.options.size = s;
                if (!this.locked) {
                    this.buttons();
                }
            }

            return this.options.size;
        },

        /**
         * Checks whether a list element exists for the given index (or index range).
         *
         * @method get
         * @return bool
         * @param i {Number} The index of the (first) element.
         * @param i2 {Number} The index of the last element.
         */
        has: function(i, i2) {
            if (i2 === undefined || !i2) {
                i2 = i;
            }

            if (this.options.size !== null && i2 > this.options.size) {
                i2 = this.options.size;
            }

            for (var j = i; j <= i2; j++) {
                var e = this.get(j);
                if (!e.length || e.hasClass('jcarousel-item-placeholder')) {
                    return false;
                }
            }

            return true;
        },

        /**
         * Returns a jQuery object with list element for the given index.
         *
         * @method get
         * @return jQuery
         * @param i {Number} The index of the element.
         */
        get: function(i) {
            return $('.jcarousel-item-' + i, this.list);
        },

        /**
         * Adds an element for the given index to the list.
         * If the element already exists, it updates the inner html.
         * Returns the created element as jQuery object.
         *
         * @method add
         * @return jQuery
         * @param i {Number} The index of the element.
         * @param s {String} The innerHTML of the element.
         */
        add: function(i, s) {
            var e = this.get(i), old = 0, n = $(s);

            if (e.length === 0) {
                var c, j = $jc.intval(i);
                e = this.create(i);
                while (true) {
                    c = this.get(--j);
                    if (j <= 0 || c.length) {
                        if (j <= 0) {
                            this.list.prepend(e);
                        } else {
                            c.after(e);
                        }
                        break;
                    }
                }
            } else {
                old = this.dimension(e);
            }

            if (n.get(0).nodeName.toUpperCase() == 'LI') {
                e.replaceWith(n);
                e = n;
            } else {
                e.empty().append(s);
            }

            this.format(e.removeClass(this.className('jcarousel-item-placeholder')), i);

            var di = this.options.visible !== null ? Math.ceil(this.clipping() / this.options.visible) : null;
            var wh = this.dimension(e, di) - old;

            if (i > 0 && i < this.first) {
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - wh + 'px');
            }

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) + wh + 'px');

            return e;
        },

        /**
         * Removes an element for the given index from the list.
         *
         * @method remove
         * @return undefined
         * @param i {Number} The index of the element.
         */
        remove: function(i) {
            var e = this.get(i);

            // Check if item exists and is not currently visible
            if (!e.length || (i >= this.first && i <= this.last)) {
                return;
            }

            var d = this.dimension(e);

            if (i < this.first) {
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + d + 'px');
            }

            e.remove();

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) - d + 'px');
        },
        removeAndAnimate: function(i) {        
            var e = this.get(i);            
            var d = this.dimension(e);            
            if (i < this.first) this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + d + 'px');            
            e.remove();
            this.options.size--;            
            var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
            var li = this.list.children('li');
            var self = this;            
            if (li.size() > 0) {
                var wh = 0, i = this.options.offset;
                li.each(function() {
                    self.format(this, i++);
                    wh += self.dimension(this, di);
                });            
                this.list.css(this.wh, wh + 'px');            
            }            
            this.scroll(0,true);
            this.buttons();
        },

        /**
         * Moves the carousel forwards.
         *
         * @method next
         * @return undefined
         */
        next: function() {
            if (this.tail !== null && !this.inTail) {
                this.scrollTail(false);
            } else {
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'last') && this.options.size !== null && this.last == this.options.size) ? 1 : this.first + this.options.scroll);
            }
        },

        /**
         * Moves the carousel backwards.
         *
         * @method prev
         * @return undefined
         */
        prev: function() {
            if (this.tail !== null && this.inTail) {
                this.scrollTail(true);
            } else {
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'first') && this.options.size !== null && this.first == 1) ? this.options.size : this.first - this.options.scroll);
            }
        },

        /**
         * Scrolls the tail of the carousel.
         *
         * @method scrollTail
         * @return undefined
         * @param b {Boolean} Whether scroll the tail back or forward.
         */
        scrollTail: function(b) {
            if (this.locked || this.animating || !this.tail) {
                return;
            }

            this.pauseAuto();

            var pos  = $jc.intval(this.list.css(this.lt));

            pos = !b ? pos - this.tail : pos + this.tail;
            this.inTail = !b;

            // Save for callbacks
            this.prevFirst = this.first;
            this.prevLast  = this.last;

            this.animate(pos);
        },

        /**
         * Scrolls the carousel to a certain position.
         *
         * @method scroll
         * @return undefined
         * @param i {Number} The index of the element to scoll to.
         * @param a {Boolean} Flag indicating whether to perform animation.
         */
        scroll: function(i, a) {
            if (this.locked || this.animating) {
                return;
            }

            this.pauseAuto();
            this.animate(this.pos(i), a);
        },

        /**
         * Prepares the carousel and return the position for a certian index.
         *
         * @method pos
         * @return {Number}
         * @param i {Number} The index of the element to scoll to.
         * @param fv {Boolean} Whether to force last item to be visible.
         */
        pos: function(i, fv) {
            var pos  = $jc.intval(this.list.css(this.lt));

            if (this.locked || this.animating) {
                return pos;
            }

            if (this.options.wrap != 'circular') {
                i = i < 1 ? 1 : (this.options.size && i > this.options.size ? this.options.size : i);
            }

            var back = this.first > i;

            // Create placeholders, new list width/height
            // and new list position
            var f = this.options.wrap != 'circular' && this.first <= 1 ? 1 : this.first;
            var c = back ? this.get(f) : this.get(this.last);
            var j = back ? f : f - 1;
            var e = null, l = 0, p = false, d = 0, g;

            while (back ? --j >= i : ++j < i) {
                e = this.get(j);
                p = !e.length;
                if (e.length === 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    c[back ? 'before' : 'after' ](e);

                    if (this.first !== null && this.options.wrap == 'circular' && this.options.size !== null && (j <= 0 || j > this.options.size)) {
                        g = this.get(this.index(j));
                        if (g.length) {
                            e = this.add(j, g.clone(true));
                        }
                    }
                }

                c = e;
                d = this.dimension(e);

                if (p) {
                    l += d;
                }

                if (this.first !== null && (this.options.wrap == 'circular' || (j >= 1 && (this.options.size === null || j <= this.options.size)))) {
                    pos = back ? pos + d : pos - d;
                }
            }

            // Calculate visible items
            var clipping = this.clipping(), cache = [], visible = 0, v = 0;
            c = this.get(i - 1);
            j = i;

            while (++visible) {
                e = this.get(j);
                p = !e.length;
                if (e.length === 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    // This should only happen on a next scroll
                    if (c.length === 0) {
                        this.list.prepend(e);
                    } else {
                        c[back ? 'before' : 'after' ](e);
                    }

                    if (this.first !== null && this.options.wrap == 'circular' && this.options.size !== null && (j <= 0 || j > this.options.size)) {
                        g = this.get(this.index(j));
                        if (g.length) {
                            e = this.add(j, g.clone(true));
                        }
                    }
                }

                c = e;
                d = this.dimension(e);
                if (d === 0) {
                    throw new Error('jCarousel: No width/height set for items. This will cause an infinite loop. Aborting...');
                }

                if (this.options.wrap != 'circular' && this.options.size !== null && j > this.options.size) {
                    cache.push(e);
                } else if (p) {
                    l += d;
                }

                v += d;

                if (v >= clipping) {
                    break;
                }

                j++;
            }

             // Remove out-of-range placeholders
            for (var x = 0; x < cache.length; x++) {
                cache[x].remove();
            }

            // Resize list
            if (l > 0) {
                this.list.css(this.wh, this.dimension(this.list) + l + 'px');

                if (back) {
                    pos -= l;
                    this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - l + 'px');
                }
            }

            // Calculate first and last item
            var last = i + visible - 1;
            if (this.options.wrap != 'circular' && this.options.size && last > this.options.size) {
                last = this.options.size;
            }

            if (j > last) {
                visible = 0;
                j = last;
                v = 0;
                while (++visible) {
                    e = this.get(j--);
                    if (!e.length) {
                        break;
                    }
                    v += this.dimension(e);
                    if (v >= clipping) {
                        break;
                    }
                }
            }

            var first = last - visible + 1;
            if (this.options.wrap != 'circular' && first < 1) {
                first = 1;
            }

            if (this.inTail && back) {
                pos += this.tail;
                this.inTail = false;
            }

            this.tail = null;
            if (this.options.wrap != 'circular' && last == this.options.size && (last - visible + 1) >= 1) {
                var m = $jc.margin(this.get(last), !this.options.vertical ? 'marginRight' : 'marginBottom');
                if ((v - m) > clipping) {
                    this.tail = v - clipping - m;
                }
            }

            if (fv && i === this.options.size && this.tail) {
                pos -= this.tail;
                this.inTail = true;
            }

            // Adjust position
            while (i-- > first) {
                pos += this.dimension(this.get(i));
            }

            // Save visible item range
            this.prevFirst = this.first;
            this.prevLast  = this.last;
            this.first     = first;
            this.last      = last;

            return pos;
        },

        /**
         * Animates the carousel to a certain position.
         *
         * @method animate
         * @return undefined
         * @param p {Number} Position to scroll to.
         * @param a {Boolean} Flag indicating whether to perform animation.
         */
        animate: function(p, a) {
            if (this.locked || this.animating) {
                return;
            }

            this.animating = true;

            var self = this;
            var scrolled = function() {
                self.animating = false;

                if (p === 0) {
                    self.list.css(self.lt,  0);
                }

                if (!self.autoStopped && (self.options.wrap == 'circular' || self.options.wrap == 'both' || self.options.wrap == 'last' || self.options.size === null || self.last < self.options.size || (self.last == self.options.size && self.tail !== null && !self.inTail))) {
                    self.startAuto();
                }

                self.buttons();
                self.notify('onAfterAnimation');

                // This function removes items which are appended automatically for circulation.
                // This prevents the list from growing infinitely.
                if (self.options.wrap == 'circular' && self.options.size !== null) {
                    for (var i = self.prevFirst; i <= self.prevLast; i++) {
                        if (i !== null && !(i >= self.first && i <= self.last) && (i < 1 || i > self.options.size)) {
                            self.remove(i);
                        }
                    }
                }
            };

            this.notify('onBeforeAnimation');

            // Animate
            if (!this.options.animation || a === false) {
                this.list.css(this.lt, p + 'px');
                scrolled();
            } else {
                var o = !this.options.vertical ? (this.options.rtl ? {'right': p} : {'left': p}) : {'top': p};
                this.list.animate(o, this.options.animation, this.options.easing, scrolled);
            }
        },

        /**
         * Starts autoscrolling.
         *
         * @method auto
         * @return undefined
         * @param s {Number} Seconds to periodically autoscroll the content.
         */
        startAuto: function(s) {
            if (s !== undefined) {
                this.options.auto = s;
            }

            if (this.options.auto === 0) {
                return this.stopAuto();
            }

            if (this.timer !== null) {
                return;
            }

            this.autoStopped = false;

            var self = this;
            this.timer = window.setTimeout(function() { self.next(); }, this.options.auto * 1000);
        },

        /**
         * Stops autoscrolling.
         *
         * @method stopAuto
         * @return undefined
         */
        stopAuto: function() {
            this.pauseAuto();
            this.autoStopped = true;
        },

        /**
         * Pauses autoscrolling.
         *
         * @method pauseAuto
         * @return undefined
         */
        pauseAuto: function() {
            if (this.timer === null) {
                return;
            }

            window.clearTimeout(this.timer);
            this.timer = null;
        },

        /**
         * Sets the states of the prev/next buttons.
         *
         * @method buttons
         * @return undefined
         */
        buttons: function(n, p) {
            if (n == null) {
                n = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'first') || this.options.size === null || this.last < this.options.size);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'first') && this.options.size !== null && this.last >= this.options.size) {
                    n = this.tail !== null && !this.inTail;
                }
            }

            if (p == null) {
                p = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'last') || this.first > 1);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'last') && this.options.size !== null && this.first == 1) {
                    p = this.tail !== null && this.inTail;
                }
            }

            var self = this;

            if (this.buttonNext.size() > 0) {
                this.buttonNext.unbind(this.options.buttonNextEvent + '.jcarousel', this.funcNext);

                if (n) {
                    this.buttonNext.bind(this.options.buttonNextEvent + '.jcarousel', this.funcNext);
                }

                this.buttonNext[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);

                if (this.options.buttonNextCallback !== null && this.buttonNext.data('jcarouselstate') != n) {
                    this.buttonNext.each(function() { self.options.buttonNextCallback(self, this, n); }).data('jcarouselstate', n);
                }
            } else {
                if (this.options.buttonNextCallback !== null && this.buttonNextState != n) {
                    this.options.buttonNextCallback(self, null, n);
                }
            }

            if (this.buttonPrev.size() > 0) {
                this.buttonPrev.unbind(this.options.buttonPrevEvent + '.jcarousel', this.funcPrev);

                if (p) {
                    this.buttonPrev.bind(this.options.buttonPrevEvent + '.jcarousel', this.funcPrev);
                }

                this.buttonPrev[p ? 'removeClass' : 'addClass'](this.className('jcarousel-prev-disabled')).attr('disabled', p ? false : true);

                if (this.options.buttonPrevCallback !== null && this.buttonPrev.data('jcarouselstate') != p) {
                    this.buttonPrev.each(function() { self.options.buttonPrevCallback(self, this, p); }).data('jcarouselstate', p);
                }
            } else {
                if (this.options.buttonPrevCallback !== null && this.buttonPrevState != p) {
                    this.options.buttonPrevCallback(self, null, p);
                }
            }

            this.buttonNextState = n;
            this.buttonPrevState = p;
        },

        /**
         * Notify callback of a specified event.
         *
         * @method notify
         * @return undefined
         * @param evt {String} The event name
         */
        notify: function(evt) {
            var state = this.prevFirst === null ? 'init' : (this.prevFirst < this.first ? 'next' : 'prev');

            // Load items
            this.callback('itemLoadCallback', evt, state);

            if (this.prevFirst !== this.first) {
                this.callback('itemFirstInCallback', evt, state, this.first);
                this.callback('itemFirstOutCallback', evt, state, this.prevFirst);
            }

            if (this.prevLast !== this.last) {
                this.callback('itemLastInCallback', evt, state, this.last);
                this.callback('itemLastOutCallback', evt, state, this.prevLast);
            }

            this.callback('itemVisibleInCallback', evt, state, this.first, this.last, this.prevFirst, this.prevLast);
            this.callback('itemVisibleOutCallback', evt, state, this.prevFirst, this.prevLast, this.first, this.last);
        },

        callback: function(cb, evt, state, i1, i2, i3, i4) {
            if (this.options[cb] == null || (typeof this.options[cb] != 'object' && evt != 'onAfterAnimation')) {
                return;
            }

            var callback = typeof this.options[cb] == 'object' ? this.options[cb][evt] : this.options[cb];

            if (!$.isFunction(callback)) {
                return;
            }

            var self = this;

            if (i1 === undefined) {
                callback(self, state, evt);
            } else if (i2 === undefined) {
                this.get(i1).each(function() { callback(self, this, i1, state, evt); });
            } else {
                var call = function(i) {
                    self.get(i).each(function() { callback(self, this, i, state, evt); });
                };
                for (var i = i1; i <= i2; i++) {
                    if (i !== null && !(i >= i3 && i <= i4)) {
                        call(i);
                    }
                }
            }
        },

        create: function(i) {
            return this.format('<li></li>', i);
        },

        format: function(e, i) {
            e = $(e);
            var split = e.get(0).className.split(' ');
            for (var j = 0; j < split.length; j++) {
                if (split[j].indexOf('jcarousel-') != -1) {
                    e.removeClass(split[j]);
                }
            }
            e.addClass(this.className('jcarousel-item')).addClass(this.className('jcarousel-item-' + i)).css({
                'float': (this.options.rtl ? 'right' : 'left'),
                'list-style': 'none'
            }).attr('jcarouselindex', i);
            return e;
        },

        className: function(c) {
            return c + ' ' + c + (!this.options.vertical ? '-horizontal' : '-vertical');
        },

        dimension: function(e, d) {
            var el = e.jquery !== undefined ? e[0] : e;

            var old = !this.options.vertical ?
                (el.offsetWidth || $jc.intval(this.options.itemFallbackDimension)) + $jc.margin(el, 'marginLeft') + $jc.margin(el, 'marginRight') :
                (el.offsetHeight || $jc.intval(this.options.itemFallbackDimension)) + $jc.margin(el, 'marginTop') + $jc.margin(el, 'marginBottom');

            if (d == null || old == d) {
                return old;
            }

            var w = !this.options.vertical ?
                d - $jc.margin(el, 'marginLeft') - $jc.margin(el, 'marginRight') :
                d - $jc.margin(el, 'marginTop') - $jc.margin(el, 'marginBottom');

            $(el).css(this.wh, w + 'px');

            return this.dimension(el);
        },

        clipping: function() {
            return !this.options.vertical ?
                this.clip[0].offsetWidth - $jc.intval(this.clip.css('borderLeftWidth')) - $jc.intval(this.clip.css('borderRightWidth')) :
                this.clip[0].offsetHeight - $jc.intval(this.clip.css('borderTopWidth')) - $jc.intval(this.clip.css('borderBottomWidth'));
        },

        index: function(i, s) {
            if (s == null) {
                s = this.options.size;
            }

            return Math.round((((i-1) / s) - Math.floor((i-1) / s)) * s) + 1;
        }
    });

    $jc.extend({
        /**
         * Gets/Sets the global default configuration properties.
         *
         * @method defaults
         * @return {Object}
         * @param d {Object} A set of key/value pairs to set as configuration properties.
         */
        defaults: function(d) {
            return $.extend(defaults, d || {});
        },

        margin: function(e, p) {
            if (!e) {
                return 0;
            }

            var el = e.jquery !== undefined ? e[0] : e;

            if (p == 'marginRight' && $.browser.safari) {
                var old = {'display': 'block', 'float': 'none', 'width': 'auto'}, oWidth, oWidth2;

                $.swap(el, old, function() { oWidth = el.offsetWidth; });

                old.marginRight = 0;
                $.swap(el, old, function() { oWidth2 = el.offsetWidth; });

                return oWidth2 - oWidth;
            }

            return $jc.intval($.css(el, p));
        },

        intval: function(v) {
            v = parseInt(v, 10);
            return isNaN(v) ? 0 : v;
        }
    });

    /**
     * Creates a carousel for all matched elements.
     *
     * @example $("#mycarousel").jcarousel();
     * @before <ul id="mycarousel" class="jcarousel-skin-name"><li>First item</li><li>Second item</li></ul>
     * @result
     *
     * <div class="jcarousel-skin-name">
     *   <div class="jcarousel-container">
     *     <div class="jcarousel-clip">
     *       <ul class="jcarousel-list">
     *         <li class="jcarousel-item-1">First item</li>
     *         <li class="jcarousel-item-2">Second item</li>
     *       </ul>
     *     </div>
     *     <div disabled="disabled" class="jcarousel-prev jcarousel-prev-disabled"></div>
     *     <div class="jcarousel-next"></div>
     *   </div>
     * </div>
     *
     * @method jcarousel
     * @return jQuery
     * @param o {Hash|String} A set of key/value pairs to set as configuration properties or a method name to call on a formerly created instance.
     */
    $.fn.jcarousel = function(o) {
        if (typeof o == 'string') {
            var instance = $(this).data('jcarousel'), args = Array.prototype.slice.call(arguments, 1);
            return instance[o].apply(instance, args);
        } else {
            return this.each(function() {
                $(this).data('jcarousel', new $jc(this, o));
            });
        }
    };

})(jQuery);
/**
 * jGrowl 1.2.5
 *
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Written by Stan Lemon <stosh1985@gmail.com>
 * Last updated: 2009.12.15
 *
 * jGrowl is a jQuery plugin implementing unobtrusive userland notifications.  These 
 * notifications function similarly to the Growl Framework available for
 * Mac OS X (http://growl.info).
 *
 * To Do:
 * - Move library settings to containers and allow them to be changed per container
 *
 * Changes in 1.2.5
 * - Changed wrapper jGrowl's options usage to "o" instead of $.jGrowl.defaults
 * - Added themeState option to control 'highlight' or 'error' for jQuery UI
 * - Ammended some CSS to provide default positioning for nested usage.
 * - Changed some CSS to be prefixed with jGrowl- to prevent namespacing issues
 * - Added two new options - openDuration and closeDuration to allow 
 *   better control of notification open and close speeds, respectively 
 *   Patch contributed by Jesse Vincet.
 * - Added afterOpen callback.  Patch contributed by Russel Branca.
 *
 * Changes in 1.2.4
 * - Fixed IE bug with the close-all button
 * - Fixed IE bug with the filter CSS attribute (special thanks to gotwic)
 * - Update IE opacity CSS
 * - Changed font sizes to use "em", and only set the base style
 *
 * Changes in 1.2.3
 * - The callbacks no longer use the container as context, instead they use the actual notification
 * - The callbacks now receive the container as a parameter after the options parameter
 * - beforeOpen and beforeClose now check the return value, if it's false - the notification does
 *   not continue.  The open callback will also halt execution if it returns false.
 * - Fixed bug where containers would get confused
 * - Expanded the pause functionality to pause an entire container.
 *
 * Changes in 1.2.2
 * - Notification can now be theme rolled for jQuery UI, special thanks to Jeff Chan!
 *
 * Changes in 1.2.1
 * - Fixed instance where the interval would fire the close method multiple times.
 * - Added CSS to hide from print media
 * - Fixed issue with closer button when div { position: relative } is set
 * - Fixed leaking issue with multiple containers.  Special thanks to Matthew Hanlon!
 *
 * Changes in 1.2.0
 * - Added message pooling to limit the number of messages appearing at a given time.
 * - Closing a notification is now bound to the notification object and triggered by the close button.
 *
 * Changes in 1.1.2
 * - Added iPhone styled example
 * - Fixed possible IE7 bug when determining if the ie6 class shoudl be applied.
 * - Added template for the close button, so that it's content could be customized.
 *
 * Changes in 1.1.1
 * - Fixed CSS styling bug for ie6 caused by a mispelling
 * - Changes height restriction on default notifications to min-height
 * - Added skinned examples using a variety of images
 * - Added the ability to customize the content of the [close all] box
 * - Added jTweet, an example of using jGrowl + Twitter
 *
 * Changes in 1.1.0
 * - Multiple container and instances.
 * - Standard $.jGrowl() now wraps $.fn.jGrowl() by first establishing a generic jGrowl container.
 * - Instance methods of a jGrowl container can be called by $.fn.jGrowl(methodName)
 * - Added glue preferenced, which allows notifications to be inserted before or after nodes in the container
 * - Added new log callback which is called before anything is done for the notification
 * - Corner's attribute are now applied on an individual notification basis.
 *
 * Changes in 1.0.4
 * - Various CSS fixes so that jGrowl renders correctly in IE6.
 *
 * Changes in 1.0.3
 * - Fixed bug with options persisting across notifications
 * - Fixed theme application bug
 * - Simplified some selectors and manipulations.
 * - Added beforeOpen and beforeClose callbacks
 * - Reorganized some lines of code to be more readable
 * - Removed unnecessary this.defaults context
 * - If corners plugin is present, it's now customizable.
 * - Customizable open animation.
 * - Customizable close animation.
 * - Customizable animation easing.
 * - Added customizable positioning (top-left, top-right, bottom-left, bottom-right, center)
 *
 * Changes in 1.0.2
 * - All CSS styling is now external.
 * - Added a theme parameter which specifies a secondary class for styling, such
 *   that notifications can be customized in appearance on a per message basis.
 * - Notification life span is now customizable on a per message basis.
 * - Added the ability to disable the global closer, enabled by default.
 * - Added callbacks for when a notification is opened or closed.
 * - Added callback for the global closer.
 * - Customizable animation speed.
 * - jGrowl now set itself up and tears itself down.
 *
 * Changes in 1.0.1:
 * - Removed dependency on metadata plugin in favor of .data()
 * - Namespaced all events
 */
(function($) {

	/** jGrowl Wrapper - Establish a base jGrowl Container for compatibility with older releases. **/
	$.jGrowl = function( m , o ) {
		// To maintain compatibility with older version that only supported one instance we'll create the base container.
		if ( $('#jGrowl').size() == 0 ) 
			$('<div id="jGrowl"></div>').addClass( (o && o.position) ? o.position : $.jGrowl.defaults.position ).appendTo('body');

		// Create a notification on the container.
		$('#jGrowl').jGrowl(m,o);
	};


	/** Raise jGrowl Notification on a jGrowl Container **/
	$.fn.jGrowl = function( m , o ) {
		if ( $.isFunction(this.each) ) {
			var args = arguments;

			return this.each(function() {
				var self = this;

				/** Create a jGrowl Instance on the Container if it does not exist **/
				if ( $(this).data('jGrowl.instance') == undefined ) {
					$(this).data('jGrowl.instance', $.extend( new $.fn.jGrowl(), { notifications: [], element: null, interval: null } ));
					$(this).data('jGrowl.instance').startup( this );
				}

				/** Optionally call jGrowl instance methods, or just raise a normal notification **/
				if ( $.isFunction($(this).data('jGrowl.instance')[m]) ) {
					$(this).data('jGrowl.instance')[m].apply( $(this).data('jGrowl.instance') , $.makeArray(args).slice(1) );
				} else {
					$(this).data('jGrowl.instance').create( m , o );
				}
			});
		};
	};

	$.extend( $.fn.jGrowl.prototype , {

		/** Default JGrowl Settings **/
		defaults: {
			pool: 			0,
			header: 		'',
			group: 			'',
			sticky: 		false,
			position: 		'bottom-left',
			glue: 			'after',
			theme: 			'default',
			themeState: 	'highlight',
			corners: 		'2px',
			check: 			250,
			life: 			15000,//Thoi gian hien thi 15s            
			closeDuration:  'normal',
			openDuration:   'normal',
			easing: 		'swing',
			closer: 		true,
			closeTemplate: '&times;',
			closerTemplate: '<div>[Đóng tất cả]</div>',
			log: 			function(e,m,o) {},
			beforeOpen: 	function(e,m,o) {},
			afterOpen: 		function(e,m,o) {},
			open: 			function(e,m,o) {},
			beforeClose: 	function(e,m,o) {},
			close: 			function(e,m,o) {},
			animateOpen: 	{
				opacity: 	'show'
			},
			animateClose: 	{
				opacity: 	'hide'
			}
		},
		
		notifications: [],
		
		/** jGrowl Container Node **/
		element: 	null,
	
		/** Interval Function **/
		interval:   null,
		
		/** Create a Notification **/
		create: 	function( message , o ) {
			var o = $.extend({}, this.defaults, o);

			/* To keep backward compatibility with 1.24 and earlier, honor 'speed' if the user has set it */
			if (typeof o.speed !== 'undefined') {
				o.openDuration = o.speed;
				o.closeDuration = o.speed;
			}

			this.notifications.push({ message: message , options: o });
			
			o.log.apply( this.element , [this.element,message,o] );
		},
		
		render: 		function( notification ) {
			var self = this;
			var message = notification.message;
			var o = notification.options;

			var notification = $(
				'<div class="jGrowl-notification ' + o.themeState + ' ui-corner-all' + 
				((o.group != undefined && o.group != '') ? ' ' + o.group : '') + '">' +
				'<div class="jGrowl-close">' + o.closeTemplate + '</div>' +
				'<div class="jGrowl-header">' + o.header + '</div>' +
				'<div class="jGrowl-message">' + message + '</div></div>'
			).data("jGrowl", o).addClass(o.theme).children('div.jGrowl-close').bind("click.jGrowl", function() {
				$(this).parent().trigger('jGrowl.close');
			}).parent();


			/** Notification Actions **/
			$(notification).bind("mouseover.jGrowl", function() {
				$('div.jGrowl-notification', self.element).data("jGrowl.pause", true);
			}).bind("mouseout.jGrowl", function() {
				$('div.jGrowl-notification', self.element).data("jGrowl.pause", false);
			}).bind('jGrowl.beforeOpen', function() {
				if ( o.beforeOpen.apply( notification , [notification,message,o,self.element] ) != false ) {
					$(this).trigger('jGrowl.open');
				}
			}).bind('jGrowl.open', function() {
				if ( o.open.apply( notification , [notification,message,o,self.element] ) != false ) {
					if ( o.glue == 'after' ) {
						$('div.jGrowl-notification:last', self.element).after(notification);
					} else {
						$('div.jGrowl-notification:first', self.element).before(notification);
					}
					
					$(this).animate(o.animateOpen, o.openDuration, o.easing, function() {
						// Fixes some anti-aliasing issues with IE filters.
						if ($.browser.msie && (parseInt($(this).css('opacity'), 10) === 1 || parseInt($(this).css('opacity'), 10) === 0))
							this.style.removeAttribute('filter');

						$(this).data("jGrowl").created = new Date();
						
						$(this).trigger('jGrowl.afterOpen');
					});
				}
			}).bind('jGrowl.afterOpen', function() {
				o.afterOpen.apply( notification , [notification,message,o,self.element] );
			}).bind('jGrowl.beforeClose', function() {
				if ( o.beforeClose.apply( notification , [notification,message,o,self.element] ) != false )
					$(this).trigger('jGrowl.close');
			}).bind('jGrowl.close', function() {
				// Pause the notification, lest during the course of animation another close event gets called.
				$(this).data('jGrowl.pause', true);
				$(this).animate(o.animateClose, o.closeDuration, o.easing, function() {
					$(this).remove();
					var close = o.close.apply( notification , [notification,message,o,self.element] );

					if ( $.isFunction(close) )
						close.apply( notification , [notification,message,o,self.element] );
				});
			}).trigger('jGrowl.beforeOpen');
		
			/** Optional Corners Plugin **/
			if ( o.corners != '' && $.fn.corner != undefined ) $(notification).corner( o.corners );

			/** Add a Global Closer if more than one notification exists **/
			if ( $('div.jGrowl-notification:parent', self.element).size() > 1 && 
				 $('div.jGrowl-closer', self.element).size() == 0 && this.defaults.closer != false ) {
				$(this.defaults.closerTemplate).addClass('jGrowl-closer ui-state-highlight ui-corner-all').addClass(this.defaults.theme)
					.appendTo(self.element).animate(this.defaults.animateOpen, this.defaults.speed, this.defaults.easing)
					.bind("click.jGrowl", function() {
						$(this).siblings().trigger("jGrowl.beforeClose");

						if ( $.isFunction( self.defaults.closer ) ) {
							self.defaults.closer.apply( $(this).parent()[0] , [$(this).parent()[0]] );
						}
					});
			};
		},

		/** Update the jGrowl Container, removing old jGrowl notifications **/
		update:	 function() {
			$(this.element).find('div.jGrowl-notification:parent').each( function() {
				if ( $(this).data("jGrowl") != undefined && $(this).data("jGrowl").created != undefined && 
					 ($(this).data("jGrowl").created.getTime() + parseInt($(this).data("jGrowl").life))  < (new Date()).getTime() && 
					 $(this).data("jGrowl").sticky != true && 
					 ($(this).data("jGrowl.pause") == undefined || $(this).data("jGrowl.pause") != true) ) {

					// Pause the notification, lest during the course of animation another close event gets called.
					$(this).trigger('jGrowl.beforeClose');
				}
			});

			if ( this.notifications.length > 0 && 
				 (this.defaults.pool == 0 || $(this.element).find('div.jGrowl-notification:parent').size() < this.defaults.pool) )
				this.render( this.notifications.shift() );

			if ( $(this.element).find('div.jGrowl-notification:parent').size() < 2 ) {
				$(this.element).find('div.jGrowl-closer').animate(this.defaults.animateClose, this.defaults.speed, this.defaults.easing, function() {
					$(this).remove();
				});
			}
		},

		/** Setup the jGrowl Notification Container **/
		startup:	function(e) {
			this.element = $(e).addClass('jGrowl').append('<div class="jGrowl-notification"></div>');
			this.interval = setInterval( function() { 
				$(e).data('jGrowl.instance').update(); 
			}, parseInt(this.defaults.check));
			
			if ($.browser.msie && parseInt($.browser.version) < 7 && !window["XMLHttpRequest"]) {
				$(this.element).addClass('ie6');
			}
		},

		/** Shutdown jGrowl, removing it and clearing the interval **/
		shutdown:   function() {
			$(this.element).removeClass('jGrowl').find('div.jGrowl-notification').remove();
			clearInterval( this.interval );
		},
		
		close: 	function() {
			$(this.element).find('div.jGrowl-notification').each(function(){
				$(this).trigger('jGrowl.beforeClose');
			});
		}
	});
	
	/** Reference the Defaults Object for compatibility with older versions of jGrowl **/
	$.jGrowl.defaults = $.fn.jGrowl.prototype.defaults;

})(jQuery);